Program to find nth term in Look and Say Sequence in Python

PythonServer Side ProgrammingProgramming

Suppose we have a number n we have to generate nth term in “Look and Say” sequence. This is a sequence whose few terms are like below −

  • 1
  • 11
  • 21
  • 1211
  • 111221

The string will be read like

  • 1 (One)
  • 11 (One 1) So read the previous 1, and say “One 1”
  • 21 (Two 1) So read the previous 11, and say “Two 1”
  • 1211 (One 2 one 1) So read the previous 21, and say “One 2 one 1”
  • 111221 (One 1 one 2 two 1) So read the previous 1211, and say “One 1 one 2 two 1”

Suppose we have a number n, 1 <= n < = 30, then we have to generate nth term. To solve this, we will follow this approach −

  • set s := “1”
  • if n = 1, then return s
  • for i := 2 to n + 1
    • j := 0
    • temp := empty string
    • curr = empty string and count := 0
    • while j < length of s, do
      • if curr is empty string, then
        • curr := s[j], count := 1 and increase j by 1
      • else if curr is s[j], then
        • increase count and j by 1
      • otherwise:
        • temp := temp + count as string + curr
        • curr = empty string
        • count := 0
    • temp := temp + count as string + curr
  • return s

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution(object):
   def solve(self, n):
      s = "1"
      if n == 1:
         return s
      for i in range(2,n+1):
         j = 0
         temp = ""
         curr = ""
         count = 0
         while j <len(s):
            if curr =="":
               curr=s[j]
               count=1
               j+=1
            elif curr == s[j]:
               count+=1
               j+=1
            else:
               temp+= str(count) + curr
               curr=""
               count = 0
               temp+=str(count) + curr
               s=temp
         return s
ob = Solution()
n = 5
print(ob.solve(n))

Input

5

Output

"111221"
raja
Updated on 19-Nov-2020 07:28:45

Advertisements