0

I'm creating a simplified program of Texas hold'em and I'm trying to create a function that builds a dictionary based upon the ranks of the cards.

For example, if I have:

H1: [6c, 2c, 6d, 6h, 2h, 6s, 3s]
H2: [6c, 2c, 6d, 6h, 2h, 3s, Ad]

I want to get something that looks like: {2: [2c, 2h], 3: [3s], 6: [6c, 6d, 6h, 6s]} when I call my function for H1.
So I want to take the 7 cards and build a dictionary based upon the ranks. In this instance, I'm looking for four of a kind.

Zini
  • 909
  • 7
  • 15
  • I'd really recommend using a dedicated library for hand scoring, dealing out cards, etc. In python I suggest [https://github.com/worldveil/deuces](https://github.com/worldveil/deuces). – lollercoaster Aug 19 '14 at 05:09

1 Answers1

3
In [51]: import operator

In [52]: import itertools as IT

In [53]: H1 =  ['6c', '2c', '6d', '6h', '2h', '6s', '3s']

In [54]: {rank:list(group) for rank, group in IT.groupby(sorted(H1), key=operator.itemgetter(slice(None, -1)))}
Out[54]: {'2': ['2c', '2h'], '3': ['3s'], '6': ['6c', '6d', '6h', '6s']}

or

In [65]: {rank:list(group) for rank, group in IT.groupby(sorted(H1), key=lambda card: card[:-1])}
Out[65]: {'2': ['2c', '2h'], '3': ['3s'], '6': ['6c', '6d', '6h', '6s']}

Note that if the ten of clubs is represented by '10c' then to peel off the rank you would need operator.itemgetter(slice(None, -1)). On the other hand, if you represented the ten of clubs with 'tc', then operator.itemgetter(0) would suffice.

unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677