First time here? Check out the FAQ!

Ask Your Question
0

Is there any way to form combinations in parts ?

asked 2 years ago

sgmth gravatar image

updated 2 years ago

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

Preview: (hide)

Comments

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 ( 2 years ago )

Okay. Thanks

sgmth gravatar imagesgmth ( 2 years ago )

1 Answer

Sort by » oldest newest most voted
1

answered 2 years ago

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
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
Preview: (hide)
link

Comments

Thanks a lot.

sgmth gravatar imagesgmth ( 2 years ago )

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

Stats

Asked: 2 years ago

Seen: 272 times

Last updated: Aug 24 '22