-
Notifications
You must be signed in to change notification settings - Fork 267
/
two_sum.py
81 lines (68 loc) · 1.95 KB
/
two_sum.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
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
"""
Problem
Given an array/list A of n numbers and another number x, determines
if exists two elements in A whose sum is exactly x
Works only for different values
"""
def solution1(values, expected):
"""
Determines if exists two elements in
values whose sum is exactly expected
"""
dic = {}
for index, value in enumerate(values):
dic[value] = index
diff = expected - value
if diff not in dic:
continue
if dic[diff] != index:
return True
return False
# Works with repeated values
def solution2(values, expected):
"""
Determines if exists two elements in
values whose sum is exactly expected
"""
dic = {}
for index, value in enumerate(values):
diff = expected - value
if diff not in dic:
dic[value] = index
continue
return True
return False
if __name__ == "__main__":
values = [42, 5, 9, 9, 16, 16, 13]
print("Solution 1")
print("Should be TRUE")
print(solution1(values, 14))
print(solution1(values, 25))
print(solution1(values, 47))
print(solution1(values, 58))
print(solution1(values, 51))
print(solution1(values, 21))
print(solution1(values, 18))
print("Should be FALSE")
print(solution1(values, 32))
print(solution1(values, 9))
print(solution1(values, 59))
print(solution2(values, 5))
print(solution2(values, 10))
print(solution2(values, 100))
print("Solution 2")
print("Should be TRUE")
print(solution2(values, 14))
print(solution2(values, 25))
print(solution2(values, 47))
print(solution2(values, 58))
print(solution2(values, 32))
print(solution2(values, 18))
print(solution1(values, 51))
print(solution1(values, 21))
print("Should be FALSE")
print(solution2(values, 10))
print(solution2(values, 9))
print(solution2(values, 59))
print(solution2(values, 5))
print(solution2(values, 100))