KatInterview

Spoken Amount Decoder: English Words to Signed Integer

StringsAuto-graded · 28 test cases
MediumAuto-gradedStringsstring-parsingtokenizationhash-map

Last updated

Parse an English number phrase (up to millions, optional "negative" prefix) into its integer value using a single left-to-right pass with group accumulators.

Spoken Amount Decoder

You are given a string text that spells out a whole number in English. Return the integer it represents.

Vocabulary

The text contains only these lowercase words, separated by single spaces:

  • negative
  • zero, one, two, three, four, five, six, seven, eight, nine
  • ten, eleven, twelve, thirteen, fourteen, fifteen, sixteen, seventeen, eighteen, nineteen
  • twenty, thirty, forty, fifty, sixty, seventy, eighty, ninety
  • hundred, thousand, million

Rules

  • A negative value begins with the word negative, followed by the words for its magnitude. Otherwise the value is non-negative.
  • Numbers are written in the standard way: groups of up to three digits, each followed by thousand or million where applicable, from largest to smallest. Groups equal to zero are omitted (for example, seven million four is 7000004).
  • hundred is only used within a group of 1 to 999, never to express values of 1000 or more. For instance, 1500 is written one thousand five hundred, not fifteen hundred.
  • Tens words and units words are written as separate words (for example, thirty eight, with no hyphen).
  • The word zero only appears when the whole number is zero.

Return the value as a Python int.

Constraints

  • The result lies in the range −999,999,999 to 999,999,999.
  • text is non-empty, contains only the words listed above, and is separated by single spaces with no leading or trailing spaces.
  • The phrase is well-formed according to the rules above.

Examples

Example 1

Input: decode_spoken_number('fifteen')

Output: 15

Example 2

Input: decode_spoken_number('negative six hundred thirty eight')

Output: -638

Example 3

Input: decode_spoken_number('zero')

Output: 0

Example 4

Input: decode_spoken_number('one hundred fifty thousand two hundred')

Output: 150200

Hints

Hint 1

Think of the number as up to three groups, each worth 0 to 999, with the groups followed by a scale word (million or thousand). Which running values do you need to track?

Hint 2

Keep two accumulators: one for the group currently being built, and one for the total of groups that have been closed by a scale word. A scale word multiplies only the current group, then moves it into the total.

Hint 3

Handle the sign first (check for a leading negative word), then process the remaining words: add small-number words to the current group, multiply the current group by 100 on hundred, and flush it on thousand or million. Remember that a scale word or hundred may appear with an empty current group only if the input is unusual, so a safe fallback is to treat an empty group as 1.