-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsolution.py
More file actions
66 lines (55 loc) · 1.85 KB
/
solution.py
File metadata and controls
66 lines (55 loc) · 1.85 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
from typing import List, Dict
def operator_helper(x: int, y: int, op: str) -> int:
if op == '+':
return x + y
elif op == '-':
return x - y
elif op == '*':
return x * y
def dynamic_programming(input: str, mp: Dict[str, List[int]]) -> List[int]:
if input in mp:
return mp[input]
if input.isdigit():
mp[input] = [int(input)]
return mp[input]
ret = list()
for i, c in enumerate(input):
if c in '+-*':
str1 = input[:i]
if str1 in mp:
ret1 = mp[str1]
else:
ret1 = dynamic_programming(str1, mp)
mp[str1] = ret1
str2 = input[i + 1:]
if str2 in mp:
ret2 = mp[str2]
else:
ret2 = dynamic_programming(str2, mp)
for x in ret1:
for y in ret2:
ret.append(operator_helper(x, y, c))
mp[input] = ret
return ret
def diff_ways_to_compute_dynamic_programming(input: str) -> List[int]:
mp = dict()
return dynamic_programming(input, mp)
def diff_ways_to_compute_divide_conquer(input: str) -> List[int]:
if input.isdigit():
return [int(input)]
ret = []
for i, c in enumerate(input):
if c in '+-*':
str1 = input[:i]
str2 = input[i + 1:]
ret1 = diff_ways_to_compute_divide_conquer(str1)
ret2 = diff_ways_to_compute_divide_conquer(str2)
for x in ret1:
for y in ret2:
ret.append(operator_helper(x, y, c))
return ret
if __name__ == '__main__':
print(diff_ways_to_compute_dynamic_programming("2-1-1"))
print(diff_ways_to_compute_dynamic_programming('2*3-4*5'))
print(diff_ways_to_compute_divide_conquer("2-1-1"))
print(diff_ways_to_compute_divide_conquer("2*3-4*5"))