I am confused in this blackjack practice question at the <= 31 part

Viewed 190

One of the practice problems is to write a function that given three integers between 1 and 11, if their sum is less than or equal to 21, return their sum. If their sum exceeds 21 and there's an eleven, reduce the total sum by 10. Finally if the sum (even after adjustment) exceeds 21, return "BUST".

I don't understand why they take <= 31 in the elif statement.

def blackjack(a,b,c):
      if sum([a,b,c]) <= 21:
           return sum([a,b,c])
     elif 11 in [a,b,c] and sum([a,b,c]) <= 31:
           return sum([a,b,c])-10
     else:
           return 'BUST'

     return "BUST"
2 Answers

If the sum is 32 then reducing by 10 will leave the player with a 22, which is still bust. The reduction is only useful if the score is 31 or less.

(By the way, this logic does not handle having multiple aces correctly. If there were two aces then both of them could be reduced by 10, not just one of them. The same goes for three or four aces—or even more, if playing with more than one deck of cards.)

It is handling the case that Aces could be worth either 1 or 11. It is alright to reduce when the sum is less than 31. Otherwise, you will be bust anyway.

Consider the following cases:

A, 9, 10

If A is 11, then you will be bust, but you can make use the value 1, so in this case the sum will be 20.

A, 10, 10

If A is 11, then you will be bust, but you can make use the value 1, so in this case the sum will be 21.

A, A, A

If A is 11, then you will be bust. The problem here is that your logic is not handling multiple Aces at the same time.

Related