StyleInCode

RSS

 

American Tenpin Bowling

6 April 2025

A solution to calculate tenpin bowling scores.

Solution

""" bowling_scores.py """

# usage: python3 bowling_scores.py < bowling_games

import sys


def score(pin_falls):
    """ calculate bowling score from pin falls """
    total = 0
    bonus = 0, 0
    frame = 0
    first_roll = True
    previous_pin_fall = None

    for pins_down in pin_falls:
        if first_roll:
            frame = min(frame + 1, 10)

        total += pins_down * (1 + bonus[0])
        bonus = bonus[1], 0

        if frame < 10:
            if first_roll:
                if pins_down == 10:
                    bonus = bonus[0] + 1, bonus[1] + 1
                else:
                    first_roll = False
                    previous_pin_fall = pins_down
            else:
                if previous_pin_fall + pins_down == 10:
                    bonus = bonus[0] + 1, bonus[1]
                first_roll = True

    return total


with sys.stdin as infile:
    for line in infile:
        if line.startswith('#') or line.startswith('\n'):
            continue

        values = [int(i) for i in line.strip().split(',')]
        test_score, pins = values[0], values[1:]

        if score(pins) != test_score:
            print('Test failed.', pins, score(pins), '-->', test_score)

Categories

Links