how to make a generator use the last yielded value when it regains control

John Salerno johnjsal at NOSPAMgmail.com
Thu Apr 6 22:23:51 EDT 2006


Ok, I wrote this all by myself, which explains why it doesn't work. It 
is meant to take a number and generate the next number that follows 
according to the Morris sequence. It works for a single number, but what 
I'd like it to do is either:

1. repeat indefinitely and have the number of times controlled elsewhere 
in the program (e.g., use the morris() generator in a for loop and use 
that context to tell it when to stop)

2. just make it a function that takes a second argument, that being the 
number of times you want it to repeat itself and create numbers in the 
sequence

Here's the code so far, and any general comments are always appreciated 
as well:

def morris(seed):
     seed = list(str(seed))
     grouping = []
     nextNum = []
     for i in range(len(seed)):
         try:
             if seed[i] == seed[i + 1]:
                 grouping.append(seed[i])
             else:
                 grouping.append(seed[i])
                 nextNum.append(str(len(grouping)) + seed[i])
                 grouping = []
         except IndexError:
             grouping.append(seed[i])
             nextNum.append(str(len(grouping)) + seed[i])
             seed = ''.join(nextNum)
             yield seed

I thought the second to last line might rebind 'seed' to the new value, 
and it would use that again the next time through, but it seems to just 
keep using the original value each time and yielding the same output.



More information about the Python-list mailing list