'Python blackjack: How do I structure an if statement to determine whether an Ace should be turned into 1?
I'm trying to solve a simple coding exercise: 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 are elevens, reduce the 11's. Finally, if the sum (even after adjustment) exceeds 21, return 'BUST'
def blackjack(a,b,c):
for i in range(0,12):
if sum((a,b,c)) <= 21:
return sum((a,b,c))
elif sum ((a,b,c)) > 21 and 11 in (a,b,c):
if a == 11:
a -= 10
continue
if b == 11 and sum((a,b,c)) > 21:
b -= 10
continue
if c == 11 and sum((a,b,c)) > 21:
c -=10
break
return sum((a,b,c))
else:
return 'Bust'
print(blackjack(11,11,11))
I expected the output of print(blackjack(11,11,11)) to be 13, but I get none.
Solution 1:[1]
def blackjack(a,b,c):
Ace_count = [a,b,c].count(11)
total = sum([a,b,c])
if total <= 21:
return ("Not busted", total)
while total > 21:
if Ace_count > 0:
Ace_count -= 1
total -= 10
else:
return "Bust"
return ("Not busted", total)
print(blackjack(11,11,11))
I think this should work, returns:
('Not busted', 13)
Solution 2:[2]
def blackjack(a,b,c):
total = a+b+c
if total <= 21:
return total
elif 11 in [a,b,c] and total > 21:
new_total = total-10
if new_total > 21:
return 'Bust'
else:
return new_total
else:
return 'Bust'
Solution 3:[3]
def func(x,y,z):
if sum([x+y+z]) <= 21:
return sum([x,y,z])
elif 11 in (x, y, z) and sum((x, y, z)) <= 31:
i = 0
while 11 in [x,y,z] and sum([x,y,z]) <= 31:
i -= 10
return sum([x,y,z]) - i
else:
return 'bust'
print(func(9,9,9)) # bust
print(func(11,11,11)) # 13
print(func(11,10,9,9)) # bust
Solution 4:[4]
def blackjack(x,y,z):
tot=int(x+y+z)
if tot < 21:
return tot
elif tot > 21 and x == 11 or y == 11 or z == 11:
tot2=tot-10
return tot2
else:
return "BUST"
print(blackjack(5, 6, 7))
print(blackjack(9, 9, 9))
print(blackjack(9, 9, 11))
Solution 5:[5]
def blackjack(numbers):
if len(numbers) == 3 and max(numbers) <= 11 and min(numbers)>=1:
sum_n = sum(numbers)
res =[]
if (sum_n <= 21):
res = sum_n
else:
if 11 in numbers:
res =sum_n-10
else:
res = "BUST"
return res
else:
return "numbers length should be 3 and max is 11 and min 1"
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 | DarkLeader |
Solution 2 | David Buck |
Solution 3 | Eric Jin |
Solution 4 | faisal almashharawi |
Solution 5 | prashanth |