Ask Your Question

Is there any way to form combinations in parts ?

asked 2022-08-24 13:05:25 +0200

sgmth gravatar image

updated 2022-08-24 13:08:49 +0200

What I want to say will be clear from this.

Suppose I run this code:

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

The output is


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 flag offensive 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.

John Palmieri gravatar imageJohn Palmieri ( 2022-08-24 17:16:52 +0200 )edit

Okay. Thanks

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

1 Answer

Sort by » oldest newest most voted

answered 2022-08-24 15:05:52 +0200

Sébastien gravatar image

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
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
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
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
edit flag offensive delete link more


Thanks a lot.

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

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower


Asked: 2022-08-24 13:05:25 +0200

Seen: 109 times

Last updated: Aug 24 '22