Reputation: 147
I have multiple hands of a Blackjack game.
ex.
Player 1 = ['AD', 'AS']
Player 2 = ['6C', '3D']
Player 3 = ['TD', 'AH']
And I'm trying to get the value of each hand by referencing it to a deck value dictionary:
deckValue = {'AH':11, '2H':2,'3H':3, '4H':4, '5H':5, '6H': 6, '7H': 7, '8H':8,
'9H':9, 'TH':10, 'JH':10, 'QH':10, 'KH':10, 'AC':11, '2C':2,'3C':3,
'4C':4, '5C':5, '6C':6,'7C': 7, '8C':8, '9C':9, 'TC':10, 'JC':10,
'QC':10, 'KC':10, 'AS':11, '2S':2,'3S':3, '4S':4, '5S':5, '6S': 6,
'7S': 7, '8S':8, '9S':9, 'TS':10, 'JS':10, 'QS':10, 'KS':10,
'AD':11, '2D':2,'3D':3, '4D':4, '5D':5, '6D': 6, '7D': 7, '8D':8,
'9D':9, 'TD':10, 'JD':10, 'QD':10, 'KD':10}
Finding a value in a dictionary can be achieved with the
deckvalue.get(key)
or
deckvalue[key]
Where key would be the string in each hand ex. deckvalue.get('AH') = 11
To achieve what I'm trying to do, I'm using a for loop to go through each hand and find the total value.
def calculate_hand(pHands):
# What I have so far
total = 0
for i in pHands:
deckValue.get(pHands[i][0])
deckValue.get(pHands[i][1])
total = #value of 0 + value of 1
return
Where pHands is:
pHands = [['AD', 'AS'], ['6C', '3D'], ['TD', 'AH']]
But I'm getting a 'list indices must be integers, not list' error
I'm new to Python, so I have no clue what this is (but it's probably due to the pHands containing str elements not int elements).
How could I get individual totals for each hand?
eg.
pHands[0] = 22
pHands[1] = 9
pHands[2] = 21
Would I have to assign a new variable to save each hands total to?
Thanks for any input.
Upvotes: 3
Views: 148
Reputation: 27283
If you're iterating over a list, you don't get indices, but actually the list elements. Better:
def calculate_hand(pHands):
# What I have so far
values = []
for (card1, card2) in pHands:
total = deckValue.get(card1) + deckValue.get(card2)
values.append(total)
return values
Also, there's a more concise way to get the value of a card:
def getvalue(card):
val = card[0]
return 11 if val=="A" else 10 if val in "TQKJ" else int(val)
If you have a function like that, you can actually write the whole calculate_hand
function in single list comprehension:
def calculate_hand(pHands):
return [getvalue(card1) + getvalue(card2) for (card1, card2) in pHands]
Upvotes: 4