Deals Of The Week - hours only!Up to 80% off on all courses and bundles.-Close
Recap
Using sets to compute unique elements
Set operations
Simulating machines
12. Simulating machines with sets
Summary

Instruction

Good job! Let's try another simulation.

There are two identical containers, as shown in the picture below:

containers

Each container has a number of bowls, which is expressed as an integer from 0 to 10. Initially, both containers are half full (5 bowls). The following state changes are possible:

  1. (add): Add 1 bowl to the first container.
  2. (transfer): Transfer 1 bowl from the first container to the second container.
  3. (subtract): Remove one bowl from the second container.

If the user tries to add a bowl to a full container or remowe a bowl from an empty container, we'll assume a new state that's identical to the previous one.

Exercise

Create a function named count_states(moves) that accepts a list of integer moves as shown in the template code. Your task is to return the number of unique states (each state is a tuple representing the bowl levels) before any state is repeated, or -1 if all states are unique.

I.e., for the input [1, 2, 3, 1, 2], we return 3 because:

state #1: (5, 5)
move #1: 1 = add -> state #2 (6, 5)
move #2: 2 = transfer -> state #3 (5, 6)
move #3: 3 = subtract -> state #4 (5, 5)

State #4 is the same as state #1 after 3 moves, so we return 3.

Stuck? Here's a hint!

  1. Start by initializing two variables:
  2. current_levels = (5, 5)
    past_levels = {(5, 5)}
  3. Iterate over all moves and calculate the new levels accordingly:
    • move #1:
      new_levels = (min(first + 1, 10), second)
    • move #2:
      if first > 0 and second < 10:
        new_levels = (first - 1, second + 1)
      else:
        new_levels = (first, second)
    • move #3:
      new_levels = (first, max(second - 1, 0))
  4. Check if the new state is already in the past_levels variable. If it is, return the length of past_levels.

Return -1 if all states are unique.