-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtwo_sum.py
More file actions
107 lines (79 loc) · 1.68 KB
/
Copy pathtwo_sum.py
File metadata and controls
107 lines (79 loc) · 1.68 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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
import sys
from min_heap import read_list
import threading
def array_to_hashtable(array):
hash_table = {}
for element in array:
hash_table[element] = False
return hash_table
'''
def two_sum_algorithm(hash_table, target, array):
for element in array:
complement = target - element
if complement in hash_table and complement != element:
return True
return False
def two_sum_loop(array):
targets = [i for i in range(-10000, 10001)]
hash_table = array_to_hashtable(array)
total = 0
for target in targets:
print(total)
if two_sum_algorithm(hash_table, target, array):
total += 1
return total
'''
def two_sum_using_list(array):
array.sort()
start = 0
end = len(array) - 1
found = array_to_hashtable(array)
min = -10000
max = 10000
while start < end:
sum = array[start] + array[end]
if sum < min:
start += 1
elif sum > max:
end -= 1
else:
if array[start] != array[end]:
found[sum] = True
current_start = start
current_end = end
while True:
start += 1
sum = array[start] + array[end]
if sum < min:
break
elif sum > max:
break
else:
if array[start] != array[end]:
found[sum] = True
start = current_start
while True:
end -= 1
sum = array[start] + array[end]
if sum < min:
break
elif sum > max:
break
else:
if array[start] != array[end]:
found[sum] = True
end = current_end
start += 1
end -= 1
count = 0
for element in found:
if found[element]:
count += 1
return count
def main():
filename = 'two_sum_numbers.txt'
array = read_list(filename)
array = list(set(array))
print(two_sum_using_list(array))
if __name__ == '__main__':
main()