Last active
March 6, 2022 16:32
-
-
Save filevich/f4edbdae9a1027276c084773c47966bc to your computer and use it in GitHub Desktop.
all possible combinations and subsets of a given array
This file contains 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 cross(h, xs): | |
return [[h]+x for x in xs] | |
def combs(xs, n): | |
if n == 1: | |
return [[x] for x in xs] | |
res = [] | |
head = xs[:-n + 1] | |
for i,h in enumerate(head): | |
rest = xs[i+1:] | |
t = combs(rest,n-1) | |
c = cross(h, t) | |
res += c | |
return res | |
def subsets(xs, n): | |
res = [] | |
for i in range(1, n + 1): | |
res += combs(xs, i) | |
return res | |
print(combs([1,2,3,4,5], 3)) | |
# gives [[1, 2, 3], [1, 2, 4], [1, 2, 5], [1, 3, 4], [1, 3, 5], [1, 4, 5], [2, 3, 4], [2, 3, 5], [2, 4, 5], [3, 4, 5]] | |
print(subsets([1,2,3], 3)) | |
# gives [[1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment