最好的方法来确定是否一个序列是在Python的另一个序列

编程入门 行业动态 更新时间:2024-10-28 20:22:49
本文介绍了最好的方法来确定是否一个序列是在Python的另一个序列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

这是一个泛化字符串包含子问题(更多)任意类型。

This is a generalization of the "string contains substring" problem to (more) arbitrary types.

给定一个序列(如列表或元组),什么是确定的另一个序列是里面的最好方法是什么?作为奖励,它应该返回的元素的索引序列开始的地方:

Given an sequence (such as a list or tuple), what's the best way of determining whether another sequence is inside it? As a bonus, it should return the index of the element where the subsequence starts:

用法示例(在顺序顺序):

Example usage (Sequence in Sequence):

>>> seq_in_seq([5,6], [4,'a',3,5,6]) 3 >>> seq_in_seq([5,7], [4,'a',3,5,6]) -1 # or None, or whatever

到目前为止,我只是靠蛮力,它似乎慢,丑陋,笨拙的。

So far, I just rely on brute force and it seems slow, ugly, and clumsy.

推荐答案

我第二高德纳 - 莫里斯 - 普拉特算法。顺便说一句,你的问题(KMP的解决方案)是完全配方5.13 Python的食谱的第二版。你可以找到相关的code在$c$c.activestate/recipes/117214/

I second the Knuth-Morris-Pratt algorithm. By the way, your problem (and the KMP solution) is exactly recipe 5.13 in Python Cookbook 2nd edition. You can find the related code at code.activestate/recipes/117214/

有发现的所有的在一个给定序列中的正确序列,并应作为一个迭代:

It finds all the correct subsequences in a given sequence, and should be used as an iterator:

>>> for s in KnuthMorrisPratt([4,'a',3,5,6], [5,6]): print s 3 >>> for s in KnuthMorrisPratt([4,'a',3,5,6], [5,7]): print s (nothing)

更多推荐

最好的方法来确定是否一个序列是在Python的另一个序列

本文发布于:2023-11-29 00:03:19,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1644490.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:序列   是在   最好的   方法来   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!