Fast generation of permutations
Anton Vredegoor
anton.vredegoor at gmail.com
Sat Jan 28 05:03:13 EST 2006
Paul Rubin wrote:
> def deals():
> for i in xrange(13**5):
> cards = [(i//p) % 13 for p in (1, 13, 169, 2197, 28561)]
> yield cards
This gives hands like [0,0,0,0,1] and [0,0,0,1,0] which are
permutations of one another.
Below is a piece of code that avoids this. Here's how to interprete its
output. Suppose one gets a hand like [0,1,2,3,4]. This means that it
would be possible to create 1024 (4**5) poker hands from this, by
"coloring" the cards.
Another hand, for example [0,0,1,2,3], would allow only 384 colorings,
because the two zeros would contribute choose 2 out of 4 (colors), so 6
colorings. The other numbers remain available for 4 colorings, which
gives 6*4**3 (==384) colorings for this hand.
Similar things happen for other partionings of the hands into numbers.
In fact I am now investigating a description based on integer
partitions of the number 5. I am not sure whether I want to partition
based on colors or on numbers, that seems to arbitrary.
This is very fascinating. Maybe someday I'll make a tkinter script with
a visual tree structure allowing all kinds of numbers of "cards", and
arbitrary numbers of variables to partition by.
This would then give result sets like those strange quantum particles,
such as quarks.
Have fun,
Anton
def hands(L = [0]):
if len(L) == 6:
if L[1] != L[-1]: #no five of a kind
yield L[1:]
else:
for i in range(L[-1],13):
for H in hands(L+[i]):
yield H
def pprint(i,hand):
print '%5i: ' %i,
for x in hand:
print '%2i ' % x,
print
def test():
H = hands()
total = 0
for i,x in enumerate(H):
pprint(i,x)
if __name__=='__main__':
test()
More information about the Python-list
mailing list