-
Notifications
You must be signed in to change notification settings - Fork 17
/
count-and-say.py
34 lines (29 loc) · 993 Bytes
/
count-and-say.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class Solution(object):
def count_and_say_recursion(self, n):
if n == 1:
return "1"
else:
prev_number = self.count_and_say_recursion(n - 1)
result = []
prev_symbol = None
for symbol in prev_number:
if symbol == prev_symbol:
repeat_counter += 1
result[-1] = str(repeat_counter) + symbol
else:
repeat_counter = 1
result.append(str(repeat_counter) + symbol)
prev_symbol = symbol
return ''.join(result)
def countAndSay(self, n):
"""
:type n: int
:rtype: str
"""
return str(self.count_and_say_recursion(n))
solution = Solution()
assert solution.countAndSay(1) == "1"
assert solution.countAndSay(2) == "11"
assert solution.countAndSay(3) == "21"
assert solution.countAndSay(4) == "1211"
assert solution.countAndSay(5) == "111221"