Look and say sequence (Python)

From LiteratePrograms

Jump to: navigation, search
Other implementations: C++ | dc | Eiffel | Haskell | J | Java | Lua | OCaml | Perl | 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 len(last_value) > 0:
            match = re.match('('+last_value[0]+'+)', last_value)
            next_value += str(len(match.group(1))) + last_value[0]
            last_value = last_value[len(match.group(1)):]
	
        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)
Download code
Personal tools