Created
May 25, 2020 12:32
-
-
Save tlylt/32fd87cd73cdbe25695912173be1c861 to your computer and use it in GitHub Desktop.
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 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