Editor

Is It a Path?

Intermediate · Write the code · from How the Internet Works: Networks, Packets and Protocols

From the lesson: What is a path, and what is routing?

When one device (the sender) sends data to another (the receiver), the data rarely go straight there. They hop from device to device. A path is a sequence of directly connected devices that starts at the sender and ends at the receiver. Routing is the process of finding a path.

Read this part of the lesson

Write is_path(network, route). network is a dictionary that maps each device to the list of devices it is directly connected to, and route is a list of devices. Return True if route is a path: it has at least two devices (a sender and a receiver), and every device in it is directly connected to the next one. Otherwise return False.

net = {'A': ['B', 'C'], 'B': ['A', 'D'], 'C': ['A', 'D'], 'D': ['B', 'C', 'E'], 'E': ['D']}
is_path(net, ['A', 'B', 'D', 'E'])  ->  True
is_path(net, ['A', 'D', 'E'])       ->  False   (A and D are not directly connected)
def is_path(network, route):
# Check every pair of neighbouring devices in the route
pass

What Check runs

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

RunsExpected output
print(is_path({"A": ["B", "C"], "B": ["A", "D"], "C": ["A", "D"], "D": ["B", "C", "E"], "E": ["D"]}, ["A", "B", "D", "E"]))True
print(is_path({"A": ["B", "C"], "B": ["A", "D"], "C": ["A", "D"], "D": ["B", "C", "E"], "E": ["D"]}, ["A", "D", "E"]))False
print(is_path({"A": ["B", "C"], "B": ["A", "D"], "C": ["A", "D"], "D": ["B", "C", "E"], "E": ["D"]}, ["E", "D", "C", "A"]))True

More Networking exercises

All Python exercises · 50 practice problems