0
0
Raspberry Piprogramming~5 mins

Reaction time game in Raspberry Pi - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Reaction time game
O(1)
Understanding Time Complexity

We want to understand how the time it takes for the reaction time game code to run changes as the game runs longer or with more players.

Specifically, we ask: how does the number of steps the program does grow when the game runs?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

import time
import random

for i in range(5):
    wait = random.uniform(1, 3)
    time.sleep(wait)  # wait for random time
    start = time.time()
    input('Press Enter as fast as you can!')
    reaction = time.time() - start
    print(f'Reaction time: {reaction:.3f} seconds')

This code runs a simple reaction time game 5 times, waiting a random time before asking the player to press Enter and measuring how fast they respond.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The for-loop that repeats the reaction test 5 times.
  • How many times: Exactly 5 times, fixed and does not change with input size.
How Execution Grows With Input

Since the loop runs a fixed 5 times, the number of operations stays the same no matter what.

Input Size (n)Approx. Operations
55 reaction tests
10Still 5 reaction tests (fixed)
100Still 5 reaction tests (fixed)

Pattern observation: The number of steps does not grow with input size because the loop count is fixed.

Final Time Complexity

Time Complexity: O(1)

This means the program runs in constant time, doing the same amount of work no matter how big the input or game length might be.

Common Mistake

[X] Wrong: "The time grows with the number of seconds the player waits before pressing Enter."

[OK] Correct: Waiting time is a pause, not extra steps the program does. The program only counts how many times it runs the loop, not how long the player takes to respond.

Interview Connect

Understanding how loops and fixed repetitions affect time helps you explain how programs behave as they run longer or handle more data. This skill is useful when designing games or interactive programs on devices like Raspberry Pi.

Self-Check

"What if we changed the loop to run for a variable number of rounds based on user input? How would the time complexity change?"