Multiple range product in Python

Posted by Tyr on Stack Overflow See other posts from Stack Overflow or by Tyr
Published on 2010-04-27T00:49:18Z Indexed on 2010/04/27 0:53 UTC
Read the original article Hit count: 369

Filed under:
|
|
|

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.

© Stack Overflow or respective owner

Related posts about python

Related posts about range