Count and Say in Python


Here we will see the Count 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 := “”, curr = “” and count := 0
    • while j < length of s, do
      • if curr is “”, 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 = “”, 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 countAndSay(self, n):
      """
      :type n: int
      :rtype: str
      """
      s = "1"
      if n == 1:
         return s
      for i in range(2,n+1):
         j = 0
         temp = ""
         curr = ""
         count = 0
         while j<len(s):
            #print(curr,count)
            if curr =="":
               #print(curr)
               curr=s[j]
               count=1
               j+=1
            elif curr == s[j]:
               #print(curr)
               count+=1
               j+=1
            else:
               #print(count,curr)
               temp+= str(count) + curr
               curr=""
               count = 0
               #print(temp)
         temp+=str(count) + curr
         s=temp
      return s
ob1 = Solution()
print(ob1.countAndSay(6))

Input

print(ob1.countAndSay(6))

Output

312211

Updated on: 28-Apr-2020

923 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements