Created
November 10, 2014 16:46
-
-
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
This file contains hidden or 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
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