vendredi 11 juin 2021

How to simplify 'blackjack" function for more efficiency? Simple Syntax/Function efficiency inquiry

A simple question came up in my Python course exam dealing with writing a blackjack function.

Here was the question:

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 by 10. Finally, if the sum (even after the adjustment) exceeds 21, return 'BUST'.

The function I wrote is below: (it works)

def blackjack(a,b,c):
    cards = [a,b,c]
    total = sum(cards)
    adjustment = total - 10
    
    if a == 11 or b == 11 or c == 11 and adjustment <= 21:
        return adjustment
    elif a == 11 or b == 11 or c == 11 and adjustment > 21:
        return 'BUST'
    elif total <= 21:
        return total
    else:
        return 'BUST'

Correct Outputs would are as follows:

blackjack(5,6,7)
18

blackjack(9,9,9)
'BUST'

blackjack(9,9,11)
19

What I find most difficult when learning Python, isn't theory or 'flow'. It's more about efficiency and the proper syntax for said efficiency.

While my end goal of 'writing style' isn't to have a bunch of messy 'harder to read' list comprehension one-liners, I'm earnestly seeking knowledge of how to combine methods and built-in functions in a readable and elegant way. So if you see any corners that could be cut in the above code to achieve the same result, I would love to learn from you.

Aucun commentaire:

Enregistrer un commentaire