Skip to content

Instantly share code, notes, and snippets.

@cjessamy
Forked from dougwt/combinations.py
Created July 21, 2016 16:08
Show Gist options
  • Save cjessamy/bfdebb77c476fb1d1d7ec8a4ec3cddf1 to your computer and use it in GitHub Desktop.
Save cjessamy/bfdebb77c476fb1d1d7ec8a4ec3cddf1 to your computer and use it in GitHub Desktop.
Python: All Possible Combinations
def combinations(n, list, combos=[]):
# initialize combos during the first pass through
if combos is None:
combos = []
if len(list) == n:
# when list has been dwindeled down to size n
# check to see if the combo has already been found
# if not, add it to our list
if combos.count(list) == 0:
combos.append(list)
combos.sort()
return combos
else:
# for each item in our list, make a recursive
# call to find all possible combos of it and
# the remaining items
for i in range(len(list)):
refined_list = list[:i] + list[i+1:]
combos = combinations(n, refined_list, combos)
return combos
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment