Editor

Settings With Clear Errors

#607 · Errors and exceptions · Intermediate · 75 XP · about 15 min

A game reads its settings from lines of text such as 'volume = 7'. When a line is wrong, a vague crash is no help: the player needs to know which line to fix.

Write parse_settings(lines) that returns a dictionary mapping each setting's name to its whole-number value, in the order they appear. Spaces around names and values are ignored. Blank lines, and lines whose first character other than a space is # (comments), are skipped.

At the first wrong line, raise a ValueError whose message starts with that line's number. Lines are counted from 1, and blank lines and comments count. Check each line in this order:

  • No = in the line: 'line 3: missing ='.
  • Nothing before the first =: 'line 3: missing name'.
  • A value that is not a whole number: "line 3: 'loud' is not a whole number", with the value as written, spaces around it removed.
  • A name that was set on an earlier line: "line 3: 'volume' is set twice".

Examples

parse_settings(['# sound', 'volume = 7', 'music=3'])
# returns {'volume': 7, 'music': 3}
parse_settings(['volume = 7', '', 'level = hard'])
# raises ValueError: line 3: 'hard' is not a whole number

Constraints

  • At most 10,000 lines.

Fastest solvers

Leaderboard

First solves only, ranked by stars and then time.