John Salerno wrote: > 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
Definitely go for (1). The Morris sequence is a great candidate to implement as a generator. As a generator, it will be more flexible and efficient than (2). def morris(num): """Generate the Morris sequence starting at num.""" num = str(num) yield num while True: result, cur, run = [], None, 0 for digit in num+'\n': if digit == cur: run += 1 else: if cur is not None: result.append(str(run)) result.append(cur) cur, run = digit, 1 num = ''.join(result) yield num # Example usage: from itertools import islice for n in islice(morris(1), 10): print n # Output: """ 1 11 21 1211 111221 312211 13112221 1113213211 31131211131221 13211311123113112211 """ --Ben -- http://mail.python.org/mailman/listinfo/python-list