loading...

re: Daily Challenge #128 - Blackjack Scorer VIEW POST

FULL DISCUSSION
 

My solution uses itertools.product to compute possible variations of Ace counting.

from itertools import product


def score(hand):
    royalty = ('J', 'Q', 'K',)
    ace = ('A',)
    aces = 0
    _score = 0

    for card in hand:
        if card in royalty:
            _score += 10
        elif card not in ace:
            _score += int(card)
        else:
            aces += 1

    if aces == 0:
        return _score

    aces_combinations = []

    variations = [_score + sum(ace_values) for ace_values in product((1,11), repeat=aces)]

    variations_vs_delta = [abs(21 - _s) for _s in variations]
    return variations[variations_vs_delta.index(min(variations_vs_delta))]


def bj_score(hand):
    s = score(hand)
    if s > 21:
        print 'Busted!'
    return s



cases = [
    ["A"],
    ["A", "J"],
    ["A", "10", "A"],
    ["5", "3", "7"],
    ["5", "4", "3", "2", "A", "K"]
]

for case in cases:
    print(case)
    print(bj_score(case))

code of conduct - report abuse