tags:

views:

241

answers:

5

What is the best way to store the cards and suits in python so that I can hold a reference to these values in another variable?

For example, if I have a list called hand (cards in players hand), how could I hold values that could refer to the names of suits and values of specific cards, and how would these names and values of suits and cards be stored?

+3  A: 

The simplest thing would be to use a list of tuples, where the cards are ints and the suits are strings:

hand = [(1, 'spade'), (10, 'club'), ...]

But simplest may not be what you want. Maybe you want a class to represent a card:

class Card:
    def __init__(self, rank, suit):
        self.rank = rank
        self.suit = suit

    def __repr__(self):
        letters = {1:'A', 11:'J', 12:'Q', 13:'K'}
        letter = letters.get(self.rank, str(self.rank))
        return "<Card %s %s>" % (letter, self.suit)

hand = [Card(1, 'spade'), Card(10, 'club')]
Ned Batchelder
+1  A: 

You could simply use a number, and decide on a mapping between number and "card". For example:

number MOD 13 = face value (after a +1)

number DIV 13 = suit

It should be noted that you'd use values from 0 to 51 for this method for each card. Then you could assign each suit a number from 0 to 3.
Jacob Schlather
+9  A: 

Poker servers tend to use a 2-character string to identify each card, which is nice because it's easy to deal with programmatically and just as easy to read for a human.

>>> import random
>>> import itertools
>>> SUITS = ('c', 'd', 'h', 's')
>>> RANKS = ('2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A')
>>> DECK = tuple(''.join(card) for card in itertools.product(RANKS, SUITS))
>>> hand = random.sample(DECK, 5)
>>> print hand
['Kh', 'Kc', '6c', '7d', '3d']

Edit: This is actually straight from a poker module I wrote to evaluate poker hands, you can see more here: http://pastebin.com/mzNmCdV5

FogleBird
excellent - just what I needed! Thanks
matt1024
For what it's worth, instead of using tuples for SUITS and RANKS, you can just use strings: SUITS = 'cdhs' and RANKS = '23456789TJQKA'.
Daniel Stutzbach
A: 
import collections

C, H, D, S = "CLUBS", "HEARTS", "DICE", "SPADE"
Card = collections.namedtuple("Card", "suit value")

hand = []

hand.append(Card(C, 3))
hand.append(Card(H, "A"))
hand.append(Card(D, 10))
hand.append(Card(S, "Q"))

for card in hand:
    print(card.value, card.suit)
naivnomore
A: 
from random import shuffle

values = range(1, 11) + "Jack Queen King".split()
suits = "Diamonds Clubs Hearts Spades".split()
deck_of_cards = ["%s of %s" % (v, s) for v in values for s in suits]

# using 2.6/3.0 string formatting:
deck = ["{0} of {1}".format(v, s) for v in values for s in suits]
doug