In: Computer Science
The Python lookNsayNth(), given below, is a generator function that generates the digits (as characters) of the “n-th” “look-and-say number”. E.g., 1113… generates the characters ‘1’, ‘1’, ‘1’, ‘3’, etc. Use this generator to print out the 1,000,000-th to 1,000,019-th digits of the 200th “look-and-say” number. Check: your number will start with 211121… (Keep in mind that the 1st digit has index 0 if the digits were put in an array). Note that the 200th “look-and-say” number has somewhere around 10**23 digits. Extra credit for printing them all!
The python "look and say number"
def lookNsay():
'''Generate the "look and say" sequence:
1, 11, 21, 1211, 111221, 312211, 13112221, 1113213211, ...
Note that strings are returned
'''
s = '1' # s is the previous result, start with 1
while True:
yield s
c,n, result = s[0], 1, ''
for t in s[1:]:
if t==c:
n += 1
else:
result += str(n) + c
c,n = t, 1
result += str(n) + c
s = result
def saythis(prev): # Supporting function
'''Generate characters of a "look-and-say" number given a generator of
characters for the previous number.
'''
c,n = next(prev), 1
for t in prev:
if t==c:
n += 1
else:
yield str(n)
yield c
c,n = t, 1
yield str(n)
yield c
def lookNsayNth(n = 1):
'''Generate characters of the n-th value of the "look-and-say" sequence
recursively
'''
if n == 1:
yield '1'
else:
yield from saythis(lookNsayNth(n-1))
# Python 3 program to find
# n'th term in look and
# say sequence
# Returns n'th term in
# look-and-say sequence
def countnndSay(n):
# Base cases
if (n == 1):
return "1"
if (n == 2):
return "11"
# Find n'th term by generating
# all terms from 3 to n-1.
# Every term is generated using
# previous term
# Initialize previous term
s = "11"
for i in range(3, n + 1):
# In below for loop,
# previous character is
# processed in current
# iteration. That is why
# a dummy character is
# added to make sure that
# loop runs one extra
iteration.
s += '$'
l = len(s)
cnt = 1 # Initialize count
# of matching chars
tmp = "" # Initialize i'th
# term in series
# Process previous term to
# find the next term
for j in range(1 , l):
# If current
character
# does't
match
if (s[j] != s[j
- 1]):
# Append count of
# str[j-1] to temp
tmp += str(cnt + 0)
# Append str[j-1]
tmp += s[j - 1]
# Reset count
cnt = 1
# If matches,
then increment
# count of
matching characters
else:
cnt += 1
# Update str
s = tmp
return s;
# Driver Code
N = 3
print(countnndSay(N))
# This code is contributed
# by ChitraNayal