The Artima Developer Community
Sponsored Link

Python Buzz Forum
Look and Say Numbers

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
Thomas Guest

Posts: 236
Nickname: tag
Registered: Nov, 2004

Thomas Guest likes dynamic languages.
Look and Say Numbers Posted: Sep 24, 2006 12:50 PM
Reply to this message Reply

This post originated from an RSS feed registered with Python Buzz by Thomas Guest.
Original Post: Look and Say Numbers
Feed Title: Word Aligned: Category Python
Feed URL: http://feeds.feedburner.com/WordAlignedCategoryPython
Feed Description: Dynamic languages in general. Python in particular. The adventures of a space sensitive programmer.
Latest Python Buzz Posts
Latest Python Buzz Posts by Thomas Guest
Latest Posts From Word Aligned: Category Python

Advertisement

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
    doctest.testmod()
    from itertools import islice
    for look_say_number in islice(look_and_say_numbers(), 10):
        print look_say_number

Read: Look and Say Numbers

Topic: Grid7 Venturecast #5 with Brad Webb from vSocial Previous Topic   Next Topic Topic: One reason those

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use