[Tutor] cycle w/ shuffle
kevin parks
kp8 at mac.com
Thu Apr 27 00:43:48 CEST 2006
I am trying to write a loop that iterates over a sequence and do
something x number of times. But sometimes i will need more events
(larger number x) than i have have items in the sequence, so if i need
more events that i have stuff in my sequence i would like to have the
loop reload and shuffle the deck and start all over again, reloading as
many times as necessary to get the number of events needed. I suppose i
could go around cyclically modulo the list size but i would want to
shuffle the deck before doing that again...
it seems to me that i need something like itertools cycle, except that
i need to keep track of when i have exhausted my list and then call
random.shuffle() on my sequence.
def cycle(iterable):
saved = []
for element in iterable:
yield element
saved.append(element)
while saved:
for element in saved:
yield element
def test():
seq = ('one', 'two', 'three', 'four', 'five', 'six', 'seven',
'eight', 'nine', 'ten')
loop = cycle(seq)
count = 1
for item in range(25):
print count, loop.next()
count = count + 1
if __name__ == '__main__':
test()
here i have gone through my list 2.5 times .. and somewhere after the
second and third(tho incomplete) rounds i need to shuffle... but i am
not sure how to fix that.
More information about the Tutor
mailing list