-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcan_sum.py
More file actions
73 lines (53 loc) · 1.88 KB
/
can_sum.py
File metadata and controls
73 lines (53 loc) · 1.88 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
"""
Python implementation of the third and the eleventh chapters code.
Original videos can be viewed from the following link:
https://www.youtube.com/watch?v=oBt53YbR9Kk
"""
# Third Chapter
def can_sum(target_sum: int, numbers: list):
"""
Returns a boolean value indicating if it is possible to get the given target_sum from the given list of numbers.
"""
if target_sum == 0:
return True
if target_sum < 0:
return False
for num in numbers:
remainder = target_sum - num # remainedar will be the target for the recursive function.
if (can_sum(remainder, numbers)):
return True
return False
def mem_can_sum(target_sum: int, numbers: list, memo: dict=None):
"""
Returns a boolean value indicating if it is possible to get the given target_sum from the given list of numbers.
"""
memo = {} if memo is None else memo
if target_sum in memo:
return memo[target_sum]
if target_sum == 0:
return True
if target_sum < 0:
return False
for num in numbers:
remainder = target_sum - num # remaindar will be the target for the recursive function.
if mem_can_sum(remainder, numbers, memo):
memo[target_sum] = True
return True
memo[target_sum] = False
return False
# Eleventh Chapter
def tab_can_sum(target_sum: int, numbers: list):
"""
Returns a boolean value indicating if it is possible to get the given target_sum from the given list of numbers.
Non-Recursive implementation.
"""
if target_sum < 0:
return False
table = [bool(idx in numbers) for idx in range(target_sum + 1)]
table[0] = True
for idx in range(target_sum + 1):
for number in numbers:
if idx + number > target_sum:
continue
table[idx + number] |= table[idx]
return table[target_sum]