问题
I'm doing a brute-force approach to trying to find the combination to an extension to a puzzle.
I am trying to get a large number of combinations and then test each combination to see if they fit certain criteria. I generate the combinations using Python's excellent itertools, essentially this gives me an iterator I can go over and test each one.
This returns quickly and gives me 91390 combinations to check:
itertools.combinations(range(1, 40), 4)
This takes a couple of minutes and give me 198792594 combinations to test:
itertools.combinations(range(1, 122), 5)
When I get to the next level, I need the answer to this:
itertools.combinations(range(1, 365), 6)
When I get into 6-way combinations of a set of 364... it takes a very long time. AGES. Am I inherently asking for a great deal of combinations? How does it scale?
回答1:
You calculate these numbers like this:
- Go to google.com
- type in "40 choose 4"
- type in "121 choose 5"
- type in "364 choose 6"
See wikipedia for the actual formula.
It scales like the factorial function.
回答2:
You're asking for 365 choose 6 = (365 * 364 * ... * 360) / (6 * 5 * ... * 2 * 1) = 3,151,277,509,380 combinations. That's a lot. Looping over 3 trillion elements is just not going to happen on your desktop in Python – no way.
If you're just looking for how many there are supposed to be, the formula to calculate this directly without considering all of them is on Wikipedia.
Edit: I just looked at the problem, and it seems like you're trying to solve it by considering all possible combinations of weights and seeing if they work. Brute-forcing it clearly isn't going to work in this situation – you'll have to think of a cleverer solution.
回答3:
Per the itertools documentation, the number of items returned is n! / r! / (n-r)! when 0 <= r <= n or zero when r > n
.
The memory use is small -- just enough to store the pool of n-items and the r-length result tuple.
来源:https://stackoverflow.com/questions/7942026/how-does-itertools-combinations-scale-in-python