views:

57

answers:

2

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.

A: 

I think

perms = itertools.product(*([xrange(1,7)]*num))

should work for you.

David Zaslavsky
+9  A: 

Yes. Use the repeat keyword argument:

perms = product(range(1, 7), repeat=3)

See the docs for more.

Mark Dickinson
ooh, good call, I didn't know about that. +1
David Zaslavsky
Oh, how did I miss that? I was even on that doc page. *facepalm*Thank You
Tyr