Traffic Light State Machine (match-case)

Hard ⏱ 18 min 36% acceptance ★★★★★ 4.6
Using Python 3.10+ structural pattern matching (match/case), write a function next_light(current) that models a traffic light cycle: "red" -> "green", "green" -> "yellow", "yellow" -> "red". For any other input, return "unknown" using the wildcard case _.

Examples

Example 1
Input
next_light("red")
Output
"green"
Explanation

Red transitions to green.

Example 2
Input
next_light("yellow")
Output
"red"
Explanation

Yellow transitions back to red.

Example 3
Input
next_light("blue")
Output
"unknown"
Explanation

Not a recognized state, falls to the wildcard case.

Constraints

  • current is a string.
  • Solution must use match/case, not if/elif.

Topics

Conditional Statementsmatch-case

Companies

CiscoIntel

Hints

Hint 1

Use `match current:` followed by `case "red": return "green"` style branches.

Hint 2

The wildcard pattern `case _:` must come last and catches everything else.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.