Look-and-say sequence

Revision as of 09:20, 4 April 2009 by rosettacode>Paddy3118 (Conways Look-and-say sequence)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Sequence Definition

  • Take a decimal number
  • Look at the number, visually grouping consecutive runs of the same digit.
  • Say the number, from left to right, group by group; as how many of that digit there are - followed by the digit grouped.
Task
Look-and-say sequence
You are encouraged to solve this task according to the task description, using any language you may know.
This becomes the next number of the sequence.

The sequence is from John Conway, of Conway's Game of Life fame.

An example:

  • Starting with the number 1, you have one 1 which produces 11.
  • Starting with 11, you have two ones i.e. 21
  • Starting with 21, you have one two, then one 1 i.e. 1211
  • Starting with 1211 you have one 1, one 2, then two 1's i.e. 111221

Write a program to generate successive members of the look-and-say sequence.

Python

<lang python>>>> from itertools import groupby >>> concat = .join >>> def lookandsay(number): return concat( concat([str(len(list(g))), k]) for k,g in groupby(number) )

>>> numberstring='1' >>> for i in range(10): print numberstring numberstring = lookandsay(numberstring)

1 11 21 1211 111221 312211 13112221 1113213211 31131211131221 13211311123113112211 >>> </lang>