The Yahtzee Scorer

A medium Python interview practice problem on DataDriven. Write the Python and run it against test cases, with instant feedback.

Domain
Python
Difficulty
medium
Seniority
L3
Asked in
Optimove

Problem

Given 5 dice and a category string, return the score. Categories: 'ones'..'sixes' (sum of dice matching that face), 'three_of_a_kind' (sum of all dice if at least 3 dice share a face, else 0), 'four_of_a_kind' (sum if >=4 share), 'full_house' (25 if 3 of one + 2 of another, else 0), 'small_straight' (30 if 4 consecutive faces), 'large_straight' (40 if 5 consecutive), 'yahtzee' (50 if all 5 same), 'chance' (sum of all 5).

Dice scoring. Multiple categories evaluated.

Example

Input:

dice = [2,3,2,5,2], category = "three_of_a_kind"

Output:

14

Worked solution and explanation

Why this problem exists in real interviews

This tests conditional logic driven by frequency analysis of dice values. It probes whether a candidate can implement game scoring rules cleanly using a frequency dict and dispatch on the category string.


Break down the requirements

Step 1: Build a frequency dict from the dice

Count occurrences of each face value.

Step 2: Dispatch on the category string

Map each category to its scoring logic: upper section sums matching dice, n-of-a-kind checks max frequency, full house checks the frequency pattern.

Step 3: Return the computed score

Each category returns an integer score.


The solution

Frequency-based dispatch by category
def yahtzee_score(dice: list, category: str) -> int:
    freq = {}
    for d in dice:
        freq[d] = freq.get(d, 0) + 1
    total = sum(dice)
    face_map = {"ones": 1, "twos": 2, "threes": 3, "fours": 4, "fives": 5, "sixes": 6}
    if category in face_map:
        face = face_map[category]
        result = face * freq.get(face, 0)
        return result
    max_freq = max(freq.values())
    if category == "three_of_a_kind":
        return total if max_freq >= 3 else 0
    if category == "four_of_a_kind":
        return total if max_freq >= 4 else 0
    if category == "full_house":
        freq_vals = sorted(freq.values())
        return 25 if freq_vals == [2, 3] else 0
    if category == "chance":
        return total
    return 0

Common follow-up questions