- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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
- Related Articles
- Program to find nth term in Look and Say Sequence in Python
- Count and display vowels in a string in Python
- Python program to count distinct words and count frequency of them
- Count Primes in Python
- Python Pandas – Count the rows and columns in a DataFrame
- Count Good Meals in Python
- Count positive and negative numbers in a list in Python program
- Count Elements x and x+1 Present in List in Python
- Python program to count positive and negative numbers in a list
- Python program to Count Even and Odd numbers in a List
- Explain the use of COUNT() AND SUM() in MySQL using Python?
- Difference between count() and find().count() in MongoDB?
- Difference between count(*) and count(columnName) in MySQL?
- Count unique sublists within list in Python
- Python Count set bits in a range?

Advertisements