-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path38_count_and_say.py
More file actions
44 lines (35 loc) · 1.14 KB
/
38_count_and_say.py
File metadata and controls
44 lines (35 loc) · 1.14 KB
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
35
36
37
38
39
40
41
42
43
44
import re
class Solution:
def countAndSay(self, n: int) -> str:
s = '1'
for _ in range(n - 1):
s = ''.join(str(len(group)) + digit for group, digit in re.findall(r'((.)\2*)', s))
return s
def countAndSay(self, n: int) -> str:
index = 0
spelled = "1"
while index+1 != n:
spelled = self.__spellNumber(spelled)
index += 1
return spelled
def __spellNumber(self, number_to_spell: str) -> str:
spelled = ""
count = 0
previous = ""
for index, digit in enumerate(number_to_spell):
if index == 0 or digit == previous:
count += 1
else:
spelled += str(count)
spelled += previous
count = 1
previous = digit
spelled += str(count)
spelled += previous
return spelled
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"
print(re.findall(r'((.)\2*)', "111221"))