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:
countAndSay
function takes a member of the count-and-say sequence as an argument and returns the next member in the sequence.curr
. The inner loop counts the number of times the current digit is repeated; this is stored in the variable count
.result
. For example, if one’s were counted before the function came across a , then “” 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 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