Template formatter with plural blocks

0
Sign in

Implement format_template(text: str, keys: list[str], values: list[str]) -> str. keys[i] maps to values[i]; all values are strings.

text can contain two kinds of expressions in braces:

  1. Placeholder {name}: replace it with the value of name. Whitespace around the name is ignored.
  2. Plural block {name, plural, one{...} other{...}}: the value of name must be an integer. If it is 1, use the one branch; otherwise use the other branch. If there is no one branch, use other. Inside the chosen branch, every # becomes the number. A branch may also contain placeholders, which are expanded too.

Rules:

  • Text outside expressions is copied unchanged. # outside a plural branch is a plain character.
  • An expression whose name is not in keys is left in the output unchanged.
  • Raise an error for an unmatched { or }, a block type other than plural, a plural block with no other branch, or a plural value that is not an integer.
  • 0 <= len(text) <= 10^4.

Example 1

text   = "{n, plural, one{# layer} other{# layers}} hidden"
keys   = ["n"]
values = ["4"]
→ "4 layers hidden"

With values = ["1"] the result is "1 layer hidden".

Example 2

text   = "{owner} shared {k, plural, one{# board with {team}} other{# boards with {team}}}"
keys   = ["owner", "k", "team"]
values = ["Rosa", "1", "Design"]
→ "Rosa shared 1 board with Design"

Reconstructed from the reported question; details may differ from what interviewers ask.

FigmaCodingEasy

Sign in to see the worked answer

The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.