-
Notifications
You must be signed in to change notification settings - Fork 0
/
007_encoding_counter.py
42 lines (29 loc) · 1 KB
/
007_encoding_counter.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
35
36
37
38
39
40
41
42
"""
Given the mapping a = 1, b = 2, ... z = 26, and an encoded message,
count the number of ways it can be decoded.
For example, the message '111' would give 3, since it could be decoded
as 'aaa, 'ka', and 'ak'.
"""
def get_encoding_count(sequence, length=None):
"""Return count of possible encodings of `encoding`
:param encoding: `str` sequence of encoded letters
:param length: length of sequence. default is None
"""
if length == None:
length = len(sequence)
# Handle base cases
if length in (0, 1):
return 1
count = 0
if sequence[length - 1] > '0':
count += get_encoding_count(sequence, length - 1)
if (
sequence[length - 2] == '1' or
(sequence[length - 2] == '1' and sequence[length - 1] < '7')):
count += get_encoding_count(sequence, length - 2)
return count
if __name__ == '__main__':
sequence = '111'
print(get_encoding_count(sequence))
sequence = '1226'
print(get_encoding_count(sequence))