All Combinations
Share
Explore

All Combinations

Given this list List(’A’, ‘B’, ‘C’, ‘D’), return this result:
[A][B][C][D]
[AB][AC][AD][BC][BD][CD]
[ABC][ABD][ACD][BCD]
[ABCD]
This is how one might implement it in python. I got this from the python itertools package, but I didn’t manage to convert it to Coda language. Index incrementing (the highlighted purple part) proved difficult.
def combinations(iterable, r):
# combinations('ABCD', 2) --> AB AC AD BC BD CD
# combinations(range(4), 3) --> 012 013 023 123
pool = tuple(iterable)
poolsz = len(pool)
if r > n:
return
indices = list(range(r))
yield tuple(pool[i] for i in indices)
while True:
# make sure that we're not doing the base case (e.g. ABCD of Comb('ABCD', 4))
for i in reversed(range(r)):
if indices[i] != i + poolsz - r:
break
else:
return
indices[i] += 1
for j in range(i+1, r):
indices[j] = indices[j-1] + 1
yield tuple(pool[i] for i in indices)

Share
 
Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.