Multiple range product in Python
- by Tyr
Is there a better way to do this:
perms = product(range(1,7),range(1,7),range(1,7))
so that I can choose how many ranges I use?
I want it to be equivalent to this, but scalable.
def dice(num)
if num == 1:
perms = ((i,) for i in range(1,7))
elif num == 2:
perms = product(range(1,7),range(1,7))
elif num == 3:
perms = product(range(1,7),range(1,7),range(1,7))
#... and so on
but I know there has to be a better way.
I'm using it for counting dice outcomes.
The actual code
def dice(selection= lambda d: d[2]):
perms = itertools.product(range(1,7),range(1,7),range(1,7))
return collections.Counter(((selection(sorted(i)) for i in perms)))
where I can call it with a variety of selectors, like sum(d[0:2]) for the sum of the lowest 2 dice or d[1] to get the middle dice.