Look and Say Numbers

2006-09-24, , Comments

What’s next?

The first six look and say numbers
1 11 21 1211 111221 312211 ...

A Python Look and Say Implementation

The following implementation of the look and say sequence leans on Python’s iterators and generators, and provides an incidental example of how to use Python’s doctest module.

def look_and_say_numbers():
    """ Generate the look-and-say number sequence.

    Start from
    '1',  which we say 'one one', giving
    '11', which we say 'two ones', giving
    '21', which we say 'one two, one one', giving
    '1211' etc.

    >>> g = look_and_say_numbers()
    >>> g.next(), g.next(), g.next(), g.next()
    ('1', '11', '21', '1211')
    from itertools import groupby
    def group_length(gp):
        " Return the length of an iterable returned by groupby. "
        return sum(1 for _ in gp)
    look_say_number = "1"
    while True:
        yield look_say_number
        look_say_number = "".join([
            "%d%s" % (group_length(group), digit)
            for digit, group in groupby(look_say_number)])

if __name__ == "__main__":
    import doctest
    from itertools import islice
    for look_say_number in islice(look_and_say_numbers(), 10):
        print look_say_number