Editor

Where the Path Crosses

Advanced · Stretch · from Python Tuples: When and Why to Use Immutable Sequences

From the lesson: Python Tuples: When and Why to Use Immutable Sequences

Think about GPS coordinates. A location like (40.7128, -74.0060) represents New York City. If you accidentally changed one of those numbers, the location would point somewhere completely different. Some data simply should not change after you create it.

Read the lesson

A robot starts at (0, 0). It gets a list of moves, each a tuple (direction, steps): "N" adds 1 to y for each step, "S" takes 1 away, "E" adds 1 to x and "W" takes 1 away. The robot walks one square at a time.

Write a function first_repeat(moves) that returns the first point the robot reaches for the second time, as a tuple (x, y), or None if it never visits a point twice. The starting point counts as visited.

first_repeat([("E", 3), ("N", 1), ("W", 1), ("S", 3)])   # (2, 0)

Walking east the robot passes (1, 0), (2, 0) and (3, 0). Walking south from (2, 1) it reaches (2, 0) again.

Return the answer instead of printing it: Check prints what first_repeat() returns for its own moves, some of them hidden.

def first_repeat(moves):
pass
Solution unlocks after your first Check

What Check runs

Your code runs first, then each of these lines, and 5 more that stay hidden. The output must match exactly.

RunsExpected output
print(first_repeat([("N", 1), ("E", 1), ("S", 1), ("W", 1)]))(0, 0)
print(first_repeat([("E", 3), ("N", 2)]))None

More Tuple exercises

All Python exercises · 50 practice problems · Data Structures quiz