forked from adinloh/Algorithms-design-and-analysis
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path06a) 2SUM.py
More file actions
119 lines (86 loc) · 2.45 KB
/
06a) 2SUM.py
File metadata and controls
119 lines (86 loc) · 2.45 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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
'''
Programming assignment 6.1:
implement the 2-SUM algorithm,
that for given list of integers
and number t finds whether there are
two distinct integers x and y
in the list such that x+y = t.
Implementation alternatives:
* Naive method - O(n^2)
* Via binary search - O(n*log(n))
* Via hash table - O(n)
@author: Mikhail Dubov
'''
import sys
import threading
def TwoSum_Naive(lst, target):
'''
Naive 2-SUM algorithm.
O(n^2) time.
'''
for x in lst:
for y in lst:
if x != y and x+y == target:
return (x, y)
return None
def binarySearch(lst, x):
def _binarySearch(lst, i, j, x):
if i > j:
return None
m = i + ((j-i)>>1)
if x < lst[m]:
return _binarySearch(lst, i, m-1, x)
elif x > lst[m]:
return _binarySearch(lst, m+1, j, x)
else: # x == lst[m]
return i
return _binarySearch(lst, 0, len(lst)-1, x)
def TwoSum_BinarySearch(lst, target):
'''
2-SUM algorithm via binary search.
Expects lst to be sorted.
O(n*log(n)) time.
'''
for x in lst:
y = target-x
i = binarySearch(lst, y)
if i and x != y:
return (x, y)
return None
def TwoSum_HashTable(lst, target):
'''
2-SUM algorithm via hash table.
O(n) time.
'''
hashTable = dict()
for x in lst:
hashTable[x] = True
for x in lst:
y = target-x
if y in hashTable and x != y:
return (x, y)
return None
def main():
lines = open('HashInt.txt').read().splitlines()
data = map(lambda x: int(x), lines)
#count = 0
#for t in range(2500, 4000+1):
# if(TwoSum_Naive(data, t)):
# count += 1
#print('Naive:' + str(count))
count = 0
sorted_data = sorted(data)
for t in range(2500, 4000+1):
if(TwoSum_BinarySearch(sorted_data, t)):
count += 1
print('Via binary search: ' + str(count))
count = 0
for t in range(2500, 4000+1):
if(TwoSum_HashTable(data, t)):
count += 1
print('Via hash table: ' + str(count))
if __name__ == '__main__':
threading.stack_size(67108864) # 64MB stack
sys.setrecursionlimit(2 ** 20) # approx 1 million recursions
thread = threading.Thread(target = main) # instantiate thread object
thread.start() # run program at target