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

Lonnie Princehouse finite.automaton at gmail.com
Fri Apr 7 00:11:35 EDT 2006


The generator in your original post /does/ rebind seed, but only on the
last iteration of the loop.  You'll need to wrap that loop in another
loop if you want the generator to yield more than once.

As for "communicating" with a generator --- e.g. telling it to stop ---
this might be done by passing some kind of mutable argument to the
generator and then changing the value of that mutable object.  However,
it's not a very elegant solution, and in this case there's not really
any reason to do it.  Instead, if you want the generator to stop, just
stop asking it to yield:

for number in morris_sequence_generator(seed):
   if it_is_time_to_stop():
     break

And:
  - No need to convert str(seed) to a list!  Strings are indexable.
  - Instead of using "try...except IndexError" to detect the end of the
loop, just change the loop to range(len(seed) - 1) and do the yield
after the loop finishes.
  - Use xrange instead of range.  range is evil.

Bonus points:
  Write the generator to work on a seed which is an iterable of unknown
length.

Super bonus points:
  Print the Nth element in the sequence without holding more than N
groups of {digit, number of occurences} of state information.  You'll
need to do this if you want to get very far: According to Wikipedia,
the 70th term of the look-and-say sequence has 179,691,598 digits.




More information about the Python-list mailing list