# Is there any way to form combinations in parts ?

What I want to say will be clear from this.

Suppose I run this code:

T = Tuples((0,1),4)
comb= Combinations(T,5)
show(comb.cardinality())


The output is

4368


My concern is this that I have to use these combinations further in my code. The problem is that for 4-tuples of (0,1) the processing is instant(because only 4368 combinations), but for 300-tuples of (0,1) even after many hours it is still processing. So, I was thinking that is it possible to form combinations in parts in different codes and run these codes separately so that output is faster.

What I mean to say is that, in the above code for example, is it possible that only first, say 10% (that is 437) of the combinations are formed. Then in another code the next 10%(that is 438th to 974th) combinations are formed and so on. Or is there any other way to make this faster

edit retag close merge delete

If you don't do comb.cardinality(), the rest should basically be instant: Combinations(T, 300) produces an iterator (as in Sébastien's answer), and if you do something like for x in comb..., it will produce the entries one at a time.

( 2022-08-24 17:16:52 +0200 )edit

Okay. Thanks

( 2022-08-25 04:43:53 +0200 )edit

Sort by » oldest newest most voted

In general, one may prefer to use iterators instead of lists, because the creation of the list takes time and is not necessary:

sage: %time for i in list(range(100000000)): print(i); break
0
CPU times: user 1.56 s, sys: 1.06 s, total: 2.63 s
Wall time: 2.62 s
sage: %time for i in iter(range(100000000)): print(i); break
0
CPU times: user 25 µs, sys: 1e+03 ns, total: 26 µs
Wall time: 116 µs


Also since Python 3, range is an iterator by default:

sage: %time for i in range(100000000): print(i); break
0
CPU times: user 29 µs, sys: 1e+03 ns, total: 30 µs
Wall time: 34.1 µs


In the particular problem asked here, one may use iterators provided by the Python itertools:

sage: import itertools
sage: T = itertools.product((0,1), repeat=4)
sage: C = itertools.combinations(T, 5)
sage: %time for c in C: print(c); break
((0, 0, 0, 0), (0, 0, 0, 1), (0, 0, 1, 0), (0, 0, 1, 1), (0, 1, 0, 0))
CPU times: user 24 µs, sys: 1 µs, total: 25 µs
Wall time: 27.4 µs

more

Thanks a lot.

( 2022-08-25 04:42:11 +0200 )edit