Possible duplicate:
Illustrator for moving or sliding window in Python
I am new to programming and am learning Python. I am looking for an efficient / pythonic way to solve a problem.
I need a function that returns a list of iterations containing combinations of the parent iterative if the elements in the combination look the same as the original parent iterable.
I am not sure if it’s “sequential”, if the correct word to describe this concept as “sequential” usually means “the same element is repeated”. for example [1,1,1], 'aaa', etc.
I mean, given the list [1,2,3,4,5]:
[1,2,3] is consistent, but [1,2,4] is not. (Is there a word for this?)
The consecutive_combinations() function and the expected behavior are created here:
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 ', 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()
Is this an effective solution? Is there anything in itertools or some other pre-built module that would do this?