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


Great! Our pawn now has a list of moves to make.

Given a list of moves, we want to detect a situation when the pawn enters a position which it had already visited, for instance:



Create a function called repeated_position(current_position, moves) that, for a given position (current_position) and a list of moves (moves), returns the first position in which the pawn finds itself for the second time (if such a position exists), or -1 if all positions occupied by the pawn are different.

You can use the function next_position(current_position, move) that was created in the previous exercise.

Stuck? Here's a hint!

Create a set of positions where the pawn has already been (positions). Inside a loop, calculate the new position after a move and check if the new position is already present in the positions set. If it is, return this position. If it isn't, add the new position to the set and update the current position accordingly. If the position never repeated, return -1.