'Incorrect output for score( ) function in blackjack python program
I am trying to code a function that would take a list of integers (ranging from 1-13, representing the cards from 1 to king) resulting in a tuple where the 1st element is the total of our hand, and the 2nd element is the number of soft aces present.
Note that the function assumes an infinite deck, rather than a standard deck of 52
Here is the prompt,
In blackjack.py, implement a function called “score”:
def score(cards):The argument to this function is a list of integers representing the cards in a Blackjack hand.
This function returns a tuple. The first element of the tuple is the total value of the hand according to the scoring rules of Blackjack (see above; this is not simply the sum of the integers in the cards list). The second element of the tuple is the number of “soft” aces that remain in the hand after doing any conversions from 11 → 1 to keep the hand from going bust.
Some examples of card lists on the left and the corresponding tuple values on the right:
[ 3, 12 ]→(13, 0)
[ 5, 5, 10 ]→(20, 0)
[ 1, 5 ]→(16, 1)
[ 1, 1, 5 ]→(17, 1)
Here is my code, which produces a tuple of the same list of integers, rather than a tuple with (total_value, soft_ace_count)
import sys
import random
def get_card():
''' The function returns a random value between 1 and 13 (where 1 = Ace & 13 = King). Simulating
an infinite deck of cards '''
return random.randint(1, 13)
def score(cards):
''' This function will take a list of numbers and result in a tuple where the 1st element is the
total value of the blackjack hand. The second element is the number of soft aces present (if any)
'''
# First we begin with 0 as our total, since no cards have been dealt out
total = 0
# Code that accounts for the event that NO aces are drawn (i.e. non of them soft)
ace_found = False
soft = False
# Code that accounts for the jacks(11), queens(12), and kings(13) having a value of 10 as per
# blackjack rules
for card in cards:
if card.value >= 10:
total += 10
else:
total += card.value
# Code that accounts for the PRESENCE of aces
if card.value == 1:
ace_found = True
# Code that accounts for the even that Aces are drawn and the conditions are such that the ace('s)
# drawn can be considered "soft" (i.e. the value of the Ace can be considered 1 or 11)
if total < 12 and ace_found:
total += 10
soft = True
return total, soft
Here, the results of the code
>>>3, 12
(3, 12)
Solution 1:[1]
What do you think about this solution?
def blackjack(hand):
total = 0
soft_aces = 0
for card in hand:
if card == 1:
soft_aces += 1
total += 11
elif card > 10:
total += 10
else:
total += card
while total > 21 and soft_aces > 0:
total -= 10
soft_aces -= 1
return (total, soft_aces)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | PleSo |
