Simple Command Parser (match-case)

Hard ⏱ 18 min 28% acceptance ★★★★★ 4.6
Using Python 3.10+ pattern matching, write a function parse_command(parts) where parts is a list of strings representing a tokenized command. Match these shapes: ["quit"] -> "Exiting"; ["move", direction] -> f"Moving {direction}" for any direction value; ["add", x, y] -> the sum x + y (parts[1] and parts[2] are already integers in this case); anything else -> "Unknown command".

Examples

Example 1
Input
parse_command(["quit"])
Output
"Exiting"
Explanation

Matches the single-element pattern.

Example 2
Input
parse_command(["move", "north"])
Output
"Moving north"
Explanation

Matches the two-element move pattern, capturing direction.

Example 3
Input
parse_command(["add", 2, 3])
Output
5
Explanation

Matches the three-element add pattern and sums the captured values.

Example 4
Input
parse_command(["jump"])
Output
"Unknown command"
Explanation

Does not match any known shape.

Constraints

  • parts is a list; for the "add" case the second and third elements are integers.

Topics

Conditional Statementsmatch-case

Companies

AmazonMicrosoft

Hints

Hint 1

Use list patterns like `case ["move", direction]:` to both match shape and capture values.

Hint 2

Order matters: put the wildcard `case _:` last.

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