- Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathDecodeWay.py
More file actions
Latest commit
84 lines (77 loc) · 2.03 KB
/
Copy pathDecodeWay.py
File metadata and controls
84 lines (77 loc) · 2.03 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
74
75
76
77
78
79
80
81
82
83
84
'''
decode numbers into characters
return the number of ways to decode a number
'''
A1
B2
C3
# DICT = {}
# for i in range(26):
# DICT[i+1] = chr(ord('A') + i)
DICT=dict((i+1, chr(ord('A') +i)) foriinrange(26))
printDICT
'''
check whether the string can be decoded
Args: string
Return: whether it can bew found in the dictionary
'''
defis_valid(str1):
str_int=int(str1)
returnstr_int>=0andstr_int<=26andDICT[str_int]
'''
Return how many ways that you can decode a number based on existing dictionary
Args: Integer number
Return: number of ways to decode the number
'''
defdecode_ways1(num):
# cover the integer number to string
num_str=str(num)
# number of ways for decoding the number
num_ways=0
foriinrange(len(num_str)):
# if the substring from index 0 to i are valid,
# recursively check the rest of the string
ifis_valid(num_str[0:i+1]):
# get the rest of the string
rest=num_str[i+1:]
# the rest of the string is an empty string
# the number of ways increase one
ifnotrest:
num_ways+=1
# recursively call the function if the rest of the string can be decoded
else:
num_ways+=decode_ways1(rest)
returnnum_ways
'''
given integer number,
return all the ways that you can decode
'''
defdecode_ways2(num):
pass
'''
given the integer in string format,
return whether it can be decoded from the dictionary
'''
defvalid(char):
char_int=int(char)
returnchar_int<=26andchar_int>0andDICT[char_int]
'''
given a number and the dictionary
return how many ways the number can be decoded
'''
defdecode_number(num):
num_str=str(num)
num_ways=0
foriinrange(len(num_str)):
# Check all substrings to see if they're valid.
ifvalid(num_str[0:i+1]):
rest_of_string=num_str[i+1:]
# See if the rest of the string can be decoded.
ifnotrest_of_string:
num_ways+=1
else:
num_ways+=decode_number(rest_of_string)
else:
break
returnnum_ways
printdecode_ways1(123123)