8000 added countAndSay.py · 0ff5ec/Programming@43b43a2 · GitHub
[go: up one dir, main page]

Skip to content

Commit 43b43a2

Browse files
committed
added countAndSay.py
1 parent ff50860 commit 43b43a2

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

countAndSay.py

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
# -*- coding: utf-8 -*-
2+
'''
3+
The count-and-say sequence is the sequence of integers with the first five terms as following:
4+
5+
1. 1
6+
2. 11
7+
3. 21
8+
4. 1211
9+
5. 111221
10+
1 is read off as "one 1" or 11.
11+
11 is read off as "two 1s" or 21.
12+
21 is read off as "one 2, then one 1" or 1211.
13+
Given an integer n, generate the nth term of the count-and-say sequence.
14+
15+
Note: Each term of the sequence of integers will be represented as a string.
16+
17+
Example 1:
18+
19+
Input: 1
20+
Output: "1"
21+
Example 2:
22+
23+
Input: 4
24+
Output: "1211"
25+
'''
26+
"""
27+
:type n: int
28+
:rtype: str
29+
"""
30+
class Solution:
31+
def countAndSay(self, n):
32+
prev = "1"
33+
for i in range(2, n + 1):
34+
curr_number = prev[0]
35+
curr_count = 1
36+
result = []
37+
for j in range(1, len(prev)):
38+
if prev[j] == curr_number:
39+
curr_count += 1
40+
else:
41+
result.append(str(curr_count))
42+
result.append(curr_number)
43+
curr_number = prev[j]
44+
curr_count = 1
45+
result.append(str(curr_count))
46+
result.append(curr_number)
47+
prev = "".join(result)
48+
return prev
49+
50+
if __name__ == "__main__":
51+
sol = Solution()
52+
print(sol.countAndSay(int(raw_input('Enter the n: '))))

0 commit comments

Comments
 (0)
0