What is the count-and-say sequence algorithm?

The count-and-say sequence, also known as the look-and-say sequence, is the following sequence of numbers:

1,11,21,1211,111221,312211,...1, 11, 21, 1211, 111221, 312211, ...

Starting from 11, the best way to generate the next number in the sequence is to read the digits of the previous number, and then count​ the number of digits in groups of the same digit. For example:

svg viewer

Implementation

  • The countAndSay function takes a member of the count-and-say sequence as an argument and returns the next member in the sequence.
  • The outer loop iterates over the argument string, curr. The inner loop counts the number of times the current digit is repeated; this is stored in the variable count.
  • Once a different digit is encountered, the count and the current digit itself are appended to result. For example, if 33 one’s were counted before the function came across a 22, then “3131” will be attached to result.
# Given a value 'curr', this function returns the value
# that comes after 'curr' in the look-and-say seq.
def countAndSay(curr):
result = "" # to store the term after 'curr'
i = 0 # to iterate over 'curr'
# Need to iterate over 'curr', and also count the
# number of digits that occur in the same group
while i < len(curr):
count = 1 # To store how many times a digit occured
# Inner while loop compares current digit and the next digit
while i + 1 < len(curr) and curr[i] == curr[i+1]:
i += 1
count += 1
result += (str(count) + curr[i])
i += 1
return result
# Driver code
number = "1" # First member is always 1.
n = 6 # Number of members in the sequence
for i in range(n):
print(number)
number = countAndSay(number)

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved