Mitchell Faas Mitchell Faas - 3 years ago 86
Python Question

Making a list of all possible 5 card poker

I'm trying to make a list of all possible 5 card poker hands to use in some computations (that may be slow but is preferably somewhat speedy). Now to get a list, I wrote the following code:

import itertools

# All possible Cards:
cards = ['2s', '2h', '2d', '2c', '3s', '3h', '3d', '3c', '4s', '4h', '4d', '4c', '5s', '5h', '5d', '5c', '6s', '6h', '6d', '6c', '7s', '7h', '7d', '7c', '8s', '8h', '8d', '8c', '9s', '9h', '9d', '9c', 'Ts', 'Th', 'Td', 'Tc', 'Js', 'Jh', 'Jd', 'Jc', 'Qs', 'Qh', 'Qd', 'Qc', 'Ks', 'Kh', 'Kd', 'Kc', 'As', 'Ah', 'Ad', 'Ac']

hands = []

# Collect all non-trivial cartesian products
for element in itertools.product(cards,cards,cards,cards,cards):
c1,c2,c3,c4,c5 = element
if c1 != c2 or c1!=c3 or c1!=c4 or c1!=c5 or c2 != c3 or c2 != c4 or c2 != c5 or c3 != c4 or c3 != c5 or c4 != c5:
# Sort all elements and delete duplicates
for x in hands:
hands = [tuple(x) for x in hands]
hands = list(set(hands))
# Convert hands back to a list
hands = [list(x) for x in hands]

# Verify result

But this runs out of memory before it's completed (over 11 gigs of RAM). I'm trying to use that list so I can exhaustively test against the set of all possible hands when I try to put 2 hands up against one another.

Does anyone know how I could make this code better?

Answer Source

First, the function you are trying to create already exists: itertools.combinations. Second, try to structure your code so that you can iterate over all possible hands without putting them all in memory simultaneously.

Here is a short program that prints all possible hands, with duplicate hands removed, but never creates an in-memory list of all possible hands:

import itertools
cards = [''.join(x) for x in itertools.product('23456789TJQKA', 'shdc')]

for hand in itertools.combinations(cards, 5):
    print (hand)

If you actually need the entire list to be in memory, try:

import itertools
cards = [''.join(x) for x in itertools.product('23456789TJQKA', 'shdc')]
big_list = list(itertools.combinations(cards, 5))
print len(big_list)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download