CMU Coding Bootcamp
at main 1.6 kB view raw
1from typing import List 2 3 4def bowlingScore(frames: List[int]) -> int: 5 """Calculate the total score of a bowling game.""" 6 scores: List[int] = [] 7 next_frame = 0 8 for i in range(10): 9 frame_score = 0 10 if frames[next_frame] == 10: 11 frame_score += 10 12 if i < 10: 13 frame_score += frames[next_frame + 1] 14 if frames[i + 1] == 10: 15 frame_score += frames[next_frame + 2] 16 else: 17 frame_score += frames[next_frame + 2] 18 next_frame += 1 19 elif frames[next_frame] + frames[next_frame + 1] == 10: 20 frame_score += 10 21 frame_score += frames[next_frame + 2] 22 next_frame += 2 23 else: 24 frame_score += frames[next_frame] + frames[next_frame + 1] 25 next_frame += 2 26 scores.append(frame_score) 27 return sum(scores) 28 29 30print("Testing bowlingScore()...", end="") 31assert bowlingScore([10] * 12) == 300 32assert bowlingScore([7, 2, 8, 2, 10, 7, 1, 8, 2, 7, 3, 10, 10, 5, 4, 8, 2, 7]) == 162 33assert bowlingScore([2, 6, 2, 6, 9, 1, 10, 10, 10, 5, 1, 4, 5, 9, 0, 8, 1]) == 140 34assert ( 35 bowlingScore([6, 4, 2, 7, 8, 1, 2, 4, 6, 3, 10, 6, 2, 1, 9, 6, 4, 10, 10, 10]) 36 == 137 37) 38assert bowlingScore([8, 1, 5, 3, 4, 3, 0, 8, 9, 0, 8, 1, 3, 6, 1, 8, 5, 4, 7, 1]) == 85 39 40# Finally, verify that the function is non-mutating 41L = [7, 2, 8, 2, 10, 7, 1, 8, 2, 7, 3, 10, 10, 5, 4, 8, 2, 7] 42bowlingScore(L) 43assert L == [7, 2, 8, 2, 10, 7, 1, 8, 2, 7, 3, 10, 10, 5, 4, 8, 2, 7] 44print("Passed!")