Count and Say Program (Leetcode):
if n == 1:
return '1'
if n == 2:
return '11'
s = '11'
c = 0
t = ''
for i in range(2,n):
t = ''
c = 1
for j in range(len(s)):
if j == len(s) - 1:
t = t + str(c) + s[j]
break
if s[j] == s[j+1]:
c = c + 1
else:
t = t + str(c) + s[j]
c = 1
s = t
return t
n = int(input())
print(countAndSay(n))
Input/Output:
1. 1
2. 11
3. 21
4. 1211
5. 111221
Explanation:
If a user gives input = 1 then output is 1.
If a user gives input = 2 then it should return 11 means ONE TIME comes '1'.
If a user gives input = 3 then it should return 21 means TWO TIMES comes '1'.
If a user gives input = 4 then it should return 1211 means ONE TIME comes '2' and ONE TIME comes '1'.
All the output depends upon the previous output.
It means the output of '2' depends on the output of '1', the output of '3' depends on the output of '2'.
You can say this as Pattern Printing but here you don't have to print all the lines only return the output of that line.
Code Explanation:
The outer loop runs to "n" times because the user gives the input(n) and we need to create a pattern (but don't print it). Then in inner loop second IF statement is used to count the number of characters which are the same when it gets a different character then the ELSE part will run and print accordingly.

0 Comments
Please don't enter any spam link in comment box.
Emoji