-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathquad_combination.py
More file actions
executable file
·61 lines (51 loc) · 1.64 KB
/
quad_combination.py
File metadata and controls
executable file
·61 lines (51 loc) · 1.64 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
#!/usr/bin/python
# vim: foldlevel-0
"""
https://www.pramp.com/question/gKQ5zA52mySBOA5GALj9
Given an array of numbers arr and a number S, find 4 different numbers in arr that sum
up to S.
Write a function that gets arr and S and returns an array of 4 indices of such numbers
in arr, or null if no such combination exists.
"""
from collections import defaultdict
from itertools import product
from sets import ImmutableSet
def solution(arr, S):
"""
>>> solution([3, 7 , 1, 8, -3, 0, 2, 7, -4, -2], -8)
[2, 4, 8, 9]
"""
sum = defaultdict(list)
# for i in range(len(arr)):
# for j in range(len(arr)):
# Or:
for i, j in product(range(len(arr)), repeat=2): # O(n^2)
if i != j:
sum[arr[i]+arr[j]].append(sorted((i, j)))
for doublesum, idx1 in sum.iteritems():
idx2 = sum.get(S-doublesum)
if not idx2:
continue
for pr in product(idx1, idx2):
indices = [i for t in pr for i in t]
if len(set(indices)) == 4:
return indices
def solution1(arr, S):
"""
Same but using sets.
>>> solution1([3, 7 , 1, 8, -3, 0, 2, 7, -4, -2], -8)
[2, 4, 8, 9]
"""
pairs = defaultdict(list) # sum -> list of pairs of index
for i in range(len(arr)):
for j in range(i+1, len(arr)):
pairs[arr[i]+arr[j]].append(ImmutableSet([i, j]))
for k in pairs.keys():
if not pairs.get(S-k):
continue
for t1, t2 in zip(pairs[k], pairs[S-k]):
if len(t1.union(t2)) == 4:
return sorted(list(t1.union(t2)))
if __name__ == "__main__":
import doctest
doctest.testmod()