Skip to content

Instantly share code, notes, and snippets.

@philangist
Created November 10, 2014 16:46
Show Gist options
  • Save philangist/4547752eebc47c68bc84 to your computer and use it in GitHub Desktop.
Save philangist/4547752eebc47c68bc84 to your computer and use it in GitHub Desktop.
Find all permutations of a list of integers that add up to another integer
def find_two_tuple_permutations(n, k):
n = set(n)
valid_pairs = []
for i in n:
delta = k - i
if delta in n:
valid_pairs.append((i, delta))
return valid_pairs
def find_three_tuple_permutations(n, k):
n = set(n)
valid_triplets = []
for i in n:
delta = k - i
valid_pairs = find_two_tuple_permutations(n, delta)
for pair in valid_pairs:
valid_triplets.extend([i, valid_pairs[0], valid_pairs[1]])
return valid_triplets
n = [2, 4, 1, -56, 7]
k = 7
find_three_tuple_permutations(n, k)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment