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:
Starting from , 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:
Implementation
- The
countAndSayfunction 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 variablecount. - Once a different digit is encountered, the count and the current digit itself are appended to
result. For example, if one’s were counted before the function came across a , then “” will be attached toresult.
# 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 groupwhile i < len(curr):count = 1 # To store how many times a digit occured# Inner while loop compares current digit and the next digitwhile i + 1 < len(curr) and curr[i] == curr[i+1]:i += 1count += 1result += (str(count) + curr[i])i += 1return result# Driver codenumber = "1" # First member is always 1.n = 6 # Number of members in the sequencefor i in range(n):print(number)number = countAndSay(number)
Free Resources
Copyright ©2026 Educative, Inc. All rights reserved