Question

In: Computer Science

The Python lookNsayNth(), given below, is a generator function that generates the digits (as characters) of...

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)) 
                

Solutions

Expert Solution

# 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


Related Solutions

Given the following password generator: ● |Σ| = 94 (the printable characters on a US keyboard)...
Given the following password generator: ● |Σ| = 94 (the printable characters on a US keyboard) ● |k| = 7 ● Assume that the password generated is a random arrangement of k characters from Σ a) What is the entropy of a password generated by this system (show your work)? b) Assume an attacker has the hash and seed for a password generated by this system. The attacker also has a computer that can generate 1010 hashes per second. How...
IN PYTHON Given a string with duplicate characters in it. Write a program to generate a...
IN PYTHON Given a string with duplicate characters in it. Write a program to generate a list that only contains the duplicate characters. In other words, your new list should contain the characters which appear more than once. Suggested Approach Used two nested for loops. The first for loop iterates from 0 to range(len(input_str)). The second for loop iterates from first_loop_index + 1 to range(len(input_str)). The reason you want to start at first_loop_index + 1 in the nested inner loop...
Write the python code that generates a normal sample with given μ and σ, and the...
Write the python code that generates a normal sample with given μ and σ, and the code that calculates m (sample mean) and s (sample standard deviation) from the sample.
Write the python code that generates a normal sample with given μ and σ, and the...
Write the python code that generates a normal sample with given μ and σ, and the code that calculates m and s from the sample. Do the same using the Bayes’ estimator assuming a prior distribution for μ.
PleaSe write a GENERATOR function in Python: how to write it with yield ? XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX Thanks...
PleaSe write a GENERATOR function in Python: how to write it with yield ? XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX Thanks in advance Write /the/ generator /function/ genAccum(seq, fn), which takes in an iterable and a function fn and yields each accumulated value from applying fn to the running total and the next element. (Note: to convert an iterable into an iterator you use iter(iterable)) ''' >>> add = lambda x, y: x + y >>> mul = lambda x, y: x * y >>>...
Given n. Write a program in PYTHON to Generate all numbers with number of digits equal...
Given n. Write a program in PYTHON to Generate all numbers with number of digits equal to n, such that the digit to the right is greater than the left digit (ai+1 > ai). E.g. if n=3 (123,124,125,……129,234,…..789)
create a python function (only) that generates 10 random numbers within a specific range. Every time...
create a python function (only) that generates 10 random numbers within a specific range. Every time a number is generated, it is appended to a list (you need to initialize a list). Then the function counts how many times a number is repeated in the created list (you can choose any number to count). The function returns the list, the number you have chosen and its count. --define the function here ---
PYTHON PROBLEM Given two numbers a and b, count how many times each of the digits...
PYTHON PROBLEM Given two numbers a and b, count how many times each of the digits 0 to 9 occur in all numbers between a and b, inclusive. In order to make your code simpler, implement first the function intToList(n) that takes as input one integer n, and returns a list with the digits of n in the order they appear. For example, intToList(1964) should return [1,9,6,4]. Using the function intToList, implement the function digitsCount(a, b) that returns a list...
PYTHON Define a function named variousChanges(...) which receives one string (origst) (with letters, digits or special...
PYTHON Define a function named variousChanges(...) which receives one string (origst) (with letters, digits or special characters), possibly empty, and returns a new string containing the following. a) in those positions where the original string has an even digit, the corresponding character in the new (returned) string should have the string digit '0' b) in those positions where the original string has a vowel letter (upper or lower case), the new (returned) string should have the letter 'V'. Note that...
Use Python. Create a Shakespearean Insult Generator The generator takes one element / data chunk from...
Use Python. Create a Shakespearean Insult Generator The generator takes one element / data chunk from each list and combines them to form the Shakespearean Insult. For example - List1 - artless List2 - beef-witted List3 - barnacle Result - Thou is a artless beef-witted barnacle    Your program will have three modes. There is the automatically mode where the program will randomly select one element from each column and combine them. The second mode is the user is presented...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT