Skip to content

Instantly share code, notes, and snippets.

@josiah14
Created April 24, 2015 22:02
Show Gist options
  • Save josiah14/960a9da1e6af05fd0516 to your computer and use it in GitHub Desktop.
Save josiah14/960a9da1e6af05fd0516 to your computer and use it in GitHub Desktop.
permutation_unordered_non-duplicate.py
def inverse_natural_sum(num, start):
for i in range(start, 0, -1):
num = num - i
if num == 0: return i
if num < 0: raise ValueError("number is not a natural sum.")
def permutations_unordered_no_repeat(collection):
def reducer(acc, x):
if acc == collection[0]:
return [ (acc, y) for y in collection[1:] ] + [ (x, y) for y in collection[2:] ]
else:
start_index = len(collection) - 1 - inverse_natural_sum(len(acc), len(collection) - 1) + 2
return acc + [ (x, y) for y in collection[start_index:] ]
return reduce(reducer, collection)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment