Skip to content

Instantly share code, notes, and snippets.

@tlylt
Created May 25, 2020 12:32
Show Gist options
  • Save tlylt/32fd87cd73cdbe25695912173be1c861 to your computer and use it in GitHub Desktop.
Save tlylt/32fd87cd73cdbe25695912173be1c861 to your computer and use it in GitHub Desktop.
def combinations(lst,n):
if n == 1: # every item is a combination
return list(map(lambda x: [x], lst))
elif len(lst) == n: # there is only one combination
return [list(lst)]
else:
first = lst[0]
rest = lst[1:]
# similar to coin change, either include or not include the first item
# if include the first item, add first to the combinations of the rest items that form n-1 combi
return list(map(lambda x: [first] + x , combinations(rest, n-1))) + combinations(rest,n)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment