[Tutor] Alternating patterns
Kent Johnson
kent37 at tds.net
Wed Mar 29 05:43:38 CEST 2006
kevin parks wrote:
> I have a set that i iterate over... but each time through it i would
> like to alternate between the original set and a variation of the set
> that has one of the members of the set altered (by + or - 1)
>
> So if my original set is:
>
> [0, 2, 4, 5, 7, 9, 11]
>
> I would use that the first pass but on the second pass i might like
> the third member (4,) to become 3, (-1) resulting in : [0, 2, 3, 5, 7,
> 9, 11]
>
> But then back again to the original on the next pass (+1 back to 4,):
> [0, 2, 4, 5, 7, 9, 11]
>
> and then back: [0, 2, 3, 5, 7, 9, 11] again, etc.
> How can one make such alternating patterns?
itertools.cycle() will repeat a sequence indefinitely:
In [2]: from itertools import cycle
In [3]: i=cycle([1,2])
In [5]: for j in range(6):
...: print i.next()
...:
...:
1
2
1
2
1
2
For non-repeating sequences I would look at writing a generator function
for the sequences.
Kent
More information about the Tutor
mailing list