progress

~/problems / Iterators & parsers / Parsers and interpreters

Pick the page language from a browser header

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

medium assessment 3 levels ~40 min Stripe

Level 1 Exact matches

When a browser asks for a page, it sends an Accept-Language header: a list of the languages the reader understands, most preferred first. A web app supports only some locales (a language plus a region, written like en-US for US English or fr-CA for Canadian French). It has to pick which of its locales to offer, in the reader's order.

Write preferred_locales(header, supported) -> list[str].

  • header is a string of entries separated by commas, like "fr-CA, en-US, de-DE". Ignore every space in it, and skip empty entries ("en-US,,fr-CA," has two entries).
  • supported is a list of distinct locales the app has.
  • Return the supported locales that the header names, in the order the header names them. A locale named twice is listed once, at its first position.
  • Matching is exact and case-sensitive: en-us does not match en-US.

At this level every entry is a full tag with a region, such as en-US. Entries the app doesn't support are ignored.

preferred_locales("fr-CA, en-US, de-DE, en-US", ["en-US", "fr-CA", "es-MX"])
# ["fr-CA", "en-US"]
preferred_locales("", ["en-US"])    # []

Constraints: up to 10^5 entries and 10^5 supported locales. ⭐ Bonus: a speed test at that size earns a star if each lookup is O(1).

Level 2 unlocks when level 1 passes.

Level 3 unlocks when level 2 passes.

Topic: Parsers and interpreters. Tokenize, recursive descent, S-expressions, evaluation and type inference.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc