I have built a Blackjack simulator in Python. I need to decrease the execution time. I have used a profiler to identify key bottlenecks in the execution. The following function is responsible for about 15% of the total run time.
def value(self):
value = 0
has_ace = False
for card in self.cards:
value += card.value
if card.rank == "A":
has_ace = True
if has_ace and value <= 11:
value += 10
return value
The above function is used to calculate the score of a hand. A hand can have multiple cards. A card has a value and a rank.
In Blackjack, an Ace can be worth 1 or 11.
Is there a better way to go?
if has_ace and value <= 11: value += 10
. What if the cards include more than a single ace? E.g. 2, A, A, A? Would the value of the hand be 5 or 15? \$\endgroup\$ – Ron Klein Feb 9 '20 at 11:55