- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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

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

- if curr is empty string, then
- temp := temp + count as string + curr

- return s

Let us see the following implementation to get better understanding −

## Example

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"

- Related Questions & Answers
- Program to find nth Fibonacci term in Python
- Generating the sequence of first n look and say numbers in JavaScript
- Find nth term of the Dragon Curve Sequence in C++
- Program to find removed term from arithmetic sequence in Python
- Program to find nth term of a sequence which are divisible by a, b, c in Python
- Program to find Fibonacci series results up to nth term in Python
- Program to find nth sequence after following the given string sequence rules in Python
- C program to find nth term of given recurrence relation
- Find nth term of a given recurrence relation in Python
- Program to find Nth term divisible by a or b in C++
- Count and Say in Python
- Find Nth term (A matrix exponentiation example) in C++
- Program to print pentatope numbers upto Nth term in C
- Program to find Nth Fibonacci Number in Python
- C++ program to find nth term of the series 5, 2, 13 41,...

Advertisements