CLUB_CARDS = range(13)
DIAMONDS_CARDS = range(13, 26)
HEART_CARDS = range(26, 39)
SPADE_CARDS = range(39, 52)
CARDS = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K"]
def get_cards():
d = {k: v for k, v in zip(CLUB_CARDS, CARDS)}
d.update({k: v for k, v in zip(DIAMONDS_CARDS, CARDS)})
d.update({k: v for k, v in zip(HEART_CARDS, CARDS)})
d.update({k: v for k, v in zip(SPADE_CARDS, CARDS)})
return d
how to refactor this code?
CodePudding user response:
If the goal of refactoring is to simplify this, you can use itertools.cycle()
to cycle the cards over a range:
from itertools import cycle
CARDS = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K"]
def get_cards():
return {k: v for k,v in zip(range(52), cycle(CARDS))}
get_cards()
Which returns the same thing:
{0: 'A',
1: '2',
2: '3',
3: '4',
4: '5',
...
48: 'T',
49: 'J',
50: 'Q',
51: 'K'}
Not sure how you are using this, but since the keys are just ordered integers, this might make more sense as a list.
CodePudding user response:
Here is an alternative:
def get_cards():
suits = list('CDHS')
ranks = list('A23456789XJQK')
return {k: ' of '.join([ranks[k%13], suits[k//13]]) for k in range(52)}
print(get_cards())
# {0: 'A of C', 1: '2 of C', 2: '3 of C', 3: '4 of C', 4: '5 of C', 5: '6 of C', 6: '7 of C', 7: '8 of C', 8: '9 of C', 9: 'X of C', 10: 'J of C', 11: 'Q of C', 12: 'K of C', 13: 'A of D', 14: '2 of D', 15: '3 of D', 16: '4 of D', 17: '5 of D', 18: '6 of D', 19: '7 of D', 20: '8 of D', 21: '9 of D', 22: 'X of D', 23: 'J of D', 24: 'Q of D', 25: 'K of D', 26: 'A of H', 27: '2 of H', 28: '3 of H', 29: '4 of H', 30: '5 of H', 31: '6 of H', 32: '7 of H', 33: '8 of H', 34: '9 of H', 35: 'X of H', 36: 'J of H', 37: 'Q of H', 38: 'K of H', 39: 'A of S', 40: '2 of S', 41: '3 of S', 42: '4 of S', 43: '5 of S', 44: '6 of S', 45: '7 of S', 46: '8 of S', 47: '9 of S', 48: 'X of S', 49: 'J of S', 50: 'Q of S', 51: 'K of S'}
Or the other way around:
def get_cards():
suits = list('CDHS')
ranks = list('A23456789XJQK')
return {13*s r: ' of '.join([ranks[r], suits[s]]) for s in range(len(suits)) for r in range(len(ranks))}
print(get_cards())
# {0: 'A of C', 1: '2 of C', 2: '3 of C', 3: '4 of C', 4: '5 of C', 5: '6 of C', 6: '7 of C', 7: '8 of C', 8: '9 of C', 9: 'X of C', 10: 'J of C', 11: 'Q of C', 12: 'K of C', 13: 'A of D', 14: '2 of D', 15: '3 of D', 16: '4 of D', 17: '5 of D', 18: '6 of D', 19: '7 of D', 20: '8 of D', 21: '9 of D', 22: 'X of D', 23: 'J of D', 24: 'Q of D', 25: 'K of D', 26: 'A of H', 27: '2 of H', 28: '3 of H', 29: '4 of H', 30: '5 of H', 31: '6 of H', 32: '7 of H', 33: '8 of H', 34: '9 of H', 35: 'X of H', 36: 'J of H', 37: 'Q of H', 38: 'K of H', 39: 'A of S', 40: '2 of S', 41: '3 of S', 42: '4 of S', 43: '5 of S', 44: '6 of S', 45: '7 of S', 46: '8 of S', 47: '9 of S', 48: 'X of S', 49: 'J of S', 50: 'Q of S', 51: 'K of S'}