-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreadandsay.py
More file actions
73 lines (57 loc) · 2.18 KB
/
readandsay.py
File metadata and controls
73 lines (57 loc) · 2.18 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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
"""Read and Say sequence
The look-and-say sequence is defined as a = [1, 11, 21, 1211, 111221, ...], please include code in your application that calculates len(a[30]).
"""
def read_and_say(n):
"""Read and say sequence.
REACTO
Repeat:
Example:
1 -> one 1 ->(11)
11 -> two 1 -(21)
21 -> one 2 one 1 (1211)
1211 -> one 1 one 2 two one (111221)
111221 -> ...
<count> <number>
Action:
- count consecutive same characters
- assemble count and value of the characters in the order from left to right
- scenario 1: the char is never shown before
- scenario 2: the char has show before
- scenario 3: the current char is not the same as the previous char (shown char)
- scenario 4: the current char is the last in the string
Test code:
Optimization: time complexity O(m*n), space complexity O(n)
:param n: [description]
:return: [description]
"""
a = ["1"]
if n > len(a) - 1:
# iterate n - len(a) times
for idx in range(0, n - 1, 1):
# count
string = ""
count = 0
shown_char = None
for digit, char in enumerate(a[idx]):
if shown_char != char: # scenario 3
if shown_char: # scenario 1
# write the char when the current char doesn't equal to the previous
string += str(count)
string += shown_char
shown_char = char
count = 1
else: # scenario 2
# The char has shown before. It means the char is repetitive
count += 1
if len(a[idx]) == digit + 1: # scenario 4
# write the char when the current char is the last of the string
string += str(count)
string += char
a.append(string)
print(a)
return a
def main():
result = read_and_say(31)
print(len(result[30]))
if __name__ == "__main__":
main()