Look and say sequence (Python)

From LiteratePrograms

Jump to: navigation, search
Other implementations: C++ | dc | Eiffel | Haskell | J | Java | Lua | OCaml | Perl | PHP | Python | Ruby | Scala | sed | sh

This program is a code dump.
Code dumps are articles with little or no documentation or rearrangement of code. Please help to turn it into a literate program. Also make sure that the source of this code does consent to release it under the MIT or public domain license.

This is a simple Python program to generate look-and-say sequences such as the Conway sequence.

<<look_and_say_sequence.py>>=
import re
def look_and_say(generator, length):
    """
    Generate a look and say sequence from the generator passed in 
    of total length as given
    """
    last_value = str(generator)
    yield last_value
    for i in range(length):
        next_value = ""
        while last_value:
            match = re.match(last_value[0]+'+', last_value)
            next_value += str(len(match.group())) + last_value[0]
            last_value = last_value[match.end():]
        last_value = next_value
        yield next_value
if __name__ == "__main__":
    # For test purposes generate the first 10 terms of the Conway sequence
    conway = look_and_say(3, 10)
    print list(conway)

Alternate version using itertools.groupby() in Python 2.4:

<<look_and_say_sequence2.py>>=
import itertools
def look_and_say(generator, length):
    """
    Generate a look and say sequence from the generator passed in 
    of total length as given
    """
    value = [generator]
    yield value
    for i in range(length):
        value = sum(([len(list(g)), k]
                     for k, g in itertools.groupby(value)),
                    [])
        yield value
if __name__ == "__main__":
    # For test purposes generate the first 10 terms of the Conway sequence
    conway = look_and_say(3, 10)
    print list(conway)
Download code
Views