Created
July 1, 2015 20:02
-
-
Save jfinkels/cb88d08746be2bca0ab2 to your computer and use it in GitHub Desktop.
Solution to the 3-SUM problem in Python.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from threesum import three_sums | |
def test_three_sums(): | |
integers = [2, 4, 8, 10, -7, -10, -25] | |
expected = [(-10, 2, 8)] | |
actual = list(three_sums(integers)) | |
assert [sorted(t) for t in three_sums(integers)] == [[-10, 2, 8]] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from collections import deque | |
def three_sums(iterable): | |
S = sorted(iterable) | |
for a, slice in zip(S, (deque(S[i:]) for i in range(1, len(S) - 1))): | |
while slice: | |
b = slice[0] | |
c = slice[-1] | |
if a + b + c == 0: | |
yield a, b, c | |
if a + b + c <= 0: | |
slice.popleft() | |
if a + b + c >= 0: | |
slice.pop() | |
def has_three_sum(iterable): | |
return sum(1 for s in three_sums(iterable)) > 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment