I find source code of itertools.combinations()
function in python. It looks like this.
def combinations(iterable, r):
pool = tuple(iterable)
n = len(pool)
if r > n:
return
indices = list(range(r))
print(indices)
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
print(indices)
yield tuple(pool[i] for i in indices)
I have tuples like this:
pairs = [(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)]
I need to generate foursomes of all possible combinations, but with condition, that there will be always only two same numbers in list. So in this case this 3 list I want to generate:
((0, 1), (0, 2), (1, 3), (2, 3))
((0, 1), (0, 3), (1, 2), (2, 3))
((0, 2), (0, 3), (1, 2), (1, 3))
What I realy need is to update code of generation combinations, because in my real app I need to generate 23-nties from 80 tuples. Generation and filtering after it would take a lot of time, thats why I need to catch problem in part of generation.
You can use itertools.combinations
and then filter the result using collections.Counter
:
from collections import Counter
import itertools as it
pairs = [(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)]
result = filter(
lambda x: max(Counter(it.chain(*x)).values()) < 3,
it.combinations(pairs, 4)
)
print(list(result))
Output:
[((0, 1), (0, 2), (1, 3), (2, 3)),
((0, 1), (0, 3), (1, 2), (2, 3)),
((0, 2), (0, 3), (1, 2), (1, 3))]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.