查找连续组合

7 浏览
0 Comments

查找连续组合

我是编程新手,正在学习Python。我正在寻找一种高效/Pythonic的方法来解决一个问题。

我想要一个函数,它返回一个包含父迭代元素的组合的可迭代对象列表,只要组合中的元素以与原始父迭代元素相同的连续顺序出现。

我不确定"连续"是否是描述这个概念的正确词语,因为"连续"通常意味着"重复相同的元素",比如[1,1,1],"aaa"等等。

我的意思是,给定列表[1,2,3,4,5]:

[1,2,3]是连续的,但[1,2,4]不是。 (这个概念有没有一个词?)

这是我创建的一个名为consecutive_combinations()的函数和预期的行为:

def consecutive_combinations(iterable, consec):

begin = 0

chunks = len(iterable) + 1 - consec

return [iterable[x + begin: x + consec] for x in xrange(chunks)]

def test():

t = (1,2,3,4,5)

s = "The quick brown fox jumps over the lazy dog."

CC = consecutive_combinations

assert CC(t, 2) == [(1, 2), (2, 3), (3, 4), (4, 5)]

assert CC(t, 3) == [(1, 2, 3), (2, 3, 4), (3, 4, 5)]

assert CC(t, 4) == [(1, 2, 3, 4), (2, 3, 4, 5)]

assert CC(t, 5) == [(1, 2, 3, 4, 5)]

assert CC(s, 3) == ['The', 'he ', 'e q', ' qu', 'qui', 'uic', 'ick', 'ck ', 'k b', ' br', 'bro', 'row', 'own', 'wn ', 'n f', ' fo', 'fox', 'ox ', 'x j', ' ju', 'jum', 'ump', 'mps', 'ps ', 's o', ' ov', 'ove', 'ver', 'er ', 'r t', ' th', 'the', 'he ', 'e l', ' la', 'laz', 'azy', 'zy ', 'y d', ' do', 'dog', 'og. ']

assert CC('', 3) == []

print "All tests passed!"

test()

这是一个高效的解决方案吗?itertools或其他预构建模块中是否有类似的功能?

0
0 Comments

找到连续组合(Find consecutive combinations)的问题是出现在上述代码中。这段代码的目的是找到给定迭代器中长度为length的连续子序列。然而,这段代码可以进一步简化。

解决方法如下:

def subsequences(iterable, length):
    return [iterable[i: i + length] for i in xrange(len(iterable) - length + 1)]

以上是对问题的解决方法。

0
0 Comments

在上述内容中,出现了一个问题:如何找到连续的组合。这个问题的解决方法可以通过使用zip函数或者itertools库来实现。

zip函数的使用方法如下:

n = 3
s = "The quick brown fox jumps over the lazy dog."
zip(*(s[i:] for i in xrange(n)))

这个方法虽然不是特别高效,而且只适用于序列,但通常足以解决问题。

另一种解决方法是使用itertools库,代码如下:

from itertools import izip, islice, tee
def slices(iterable, n):
    return izip(*(islice(it, i, None) for i, it in enumerate(tee(iterable, n))))

这种方法适用于任何可迭代对象,但对于普通的序列(如列表或字符串)可能会较慢。

总结起来,通过使用zip函数或者itertools库,可以找到连续的组合。zip函数适用于序列,而itertools库适用于任何可迭代对象。

0