-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhow_sum.py
More file actions
79 lines (60 loc) · 2.16 KB
/
how_sum.py
File metadata and controls
79 lines (60 loc) · 2.16 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
"""
Python implementation of the fourth and the twelfth chapters code.
Original videos can be viewed from the following link:
https://www.youtube.com/watch?v=oBt53YbR9Kk
"""
# Fourth Chapter
def how_sum(target_sum: int, numbers: list):
"""
Returns a list containing any combination of elements that add up to exactly as input target_sum.
Returns None if target_sum can not be reached.
"""
if target_sum == 0:
return []
if target_sum < 0:
return None
for num in numbers:
remainder = target_sum - num
remainder_result = how_sum(remainder, numbers)
if remainder_result is not None:
remainder_result.append(num)
return remainder_result
return None
def mem_how_sum(target_sum: int, numbers: list, memo: dict=None):
"""
Returns a list containing any combination of elements that add up to exactly as input target_sum.
Returns None if target_sum can not be reached.
"""
memo = {} if memo is None else memo
if target_sum in memo:
return memo[target_sum]
if target_sum == 0:
return []
if target_sum < 0:
return None
for num in numbers:
remainder = target_sum - num
remainder_result = mem_how_sum(remainder, numbers, memo)
if remainder_result is not None:
remainder_result.append(num)
memo.update({target_sum: remainder_result})
return remainder_result
memo.update({target_sum: None})
return None
# Twelfth Chapter
def tab_how_sum(target_sum: int, numbers: list):
"""
Returns a list containing any combination of elements that add up to exactly as input target_sum.
Returns None if target_sum can not be reached.
"""
table = [None for _ in range(target_sum + 1)]
table[0] = []
for idx in range(target_sum + 1):
for number in numbers:
if idx + number > target_sum:
break
if table[idx] is None:
continue
if table[idx + number] is None:
table[idx + number] = list(table[idx]) + [number] # We need to copy the list, not change it.
return table[target_sum]