What I'd need is to create combinations for two elements a time.
If a list contains: seq = ['A', 'B', 'C']
the output would be com = [['A', 'B'], ['A', 'C'], ['B', 'C']]
all this without itertools.combinations
method.
I used the following code for the permutations. But how could I modify it to make it work with the combinations?
def permute(seq):
if len(seq) <= 1:
perms = [seq]
else:
perms = []
for i in range(len(seq)):
sub = permute(seq[:i]+seq[i+1:])
for p in sub:
perms.append(seq[i:i+1]+p)
return perms
In the formula of combinations without repetition, input the values: C ( n , r ) = n ! That's it! That's how you calculate the number of combinations without repetition.
The itertools. combinations() function takes two arguments—an iterable inputs and a positive integer n —and produces an iterator over tuples of all combinations of n elements in inputs .
If you don't want to use itertools
, then use the documented pure-Python equivalent:
def combinations(iterable, r):
# combinations('ABCD', 2) --> AB AC AD BC BD CD
# combinations(range(4), 3) --> 012 013 023 123
pool = tuple(iterable)
n = len(pool)
if r > n:
return
indices = range(r)
yield tuple(pool[i] for i in indices)
while True:
for i in reversed(range(r)):
if indices[i] != i + n - 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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With