Reputation: 1357
So I play a game in which I have 12 pieces of gear. Each piece of gear (for the purposes of my endeavor) has four buffs I am interested in: power, haste, critical damage, critical rating.
I have a formula in which I can enter the total power, haste, CD, and CR and generate the expected damage per second output.
However, not every piece of gear has all four buffs. Currently I am interested in two case scenarios: gear that only has one of the four, and gear that has three of the four.
In the first scenario, each of the twelve pieces of gear will have a single buff on it that can be any of the four. What I want to do is write a program that finds which arrangement outputs the most damage.
So then what I need to do is write a program that tries every possible arrangement in this scenario. If we figure that each of the twelve pieces can have one of four values, that's 4^12 possible arrangements to test - or 16,777,216 - easy-peasy for a machine, right?
However I have to loop through all these arrangements, and at the moment I can only imagine 12 nested FOR loops of value 1-4 each, with the formula in the middle.
This seems un-pythonic in terms of readability and just duplication of effort.
Is there a better, more pythonic way to check to see which my formula likes best (generates max damage), or is 12 nested FOR loops, as excessive as that seems, the best and clearest way?
Upvotes: 0
Views: 72
Reputation: 1762
Use iterator to replace for-loop:
keys = ['p', 'h', 'cd', 'cr']
iter_keys = itertools.product(*([keys] * 12))
for item in iter_keys:
print item
Output:
('p', 'p', 'p', 'p', 'p', 'cr', 'cd', 'h', 'cr', 'p', 'h', 'cr')
('p', 'p', 'p', 'p', 'p', 'cr', 'cd', 'h', 'cr', 'p', 'cd', 'p')
('p', 'p', 'p', 'p', 'p', 'cr', 'cd', 'h', 'cr', 'p', 'cd', 'h')
('p', 'p', 'p', 'p', 'p', 'cr', 'cd', 'h', 'cr', 'p', 'cd', 'cd')
('p', 'p', 'p', 'p', 'p', 'cr', 'cd', 'h', 'cr', 'p', 'cd', 'cr')
....
('cr', 'cr', 'cr', 'cr', 'cr', 'cr', 'cr', 'cr', 'cr', 'cr', 'cr', 'cr')
Upvotes: 1
Reputation: 1374
If you have 12 nested for loops, you probably need a recursive design like this :
def loops (values, num, current_list):
if num > 0:
for v in values:
loops(values, num-1, current_list+list(v))
else:
print current_list
loops (('a', 'b', 'c', 'd'), 12, [])
Then, you will probably rewrite it in a pythonic way like Mad Lee's one, but this shows the principle.
Upvotes: 0