Skip to content

Instantly share code, notes, and snippets.

@benhall-7
Created October 2, 2020 06:02
Show Gist options
  • Save benhall-7/12774f1383d874c588ca709e9a3979ea to your computer and use it in GitHub Desktop.
Save benhall-7/12774f1383d874c588ca709e9a3979ea to your computer and use it in GitHub Desktop.
Code Challenge: word representation to number conversion
ONES = {
"one": 1,
"two": 2,
"three": 3,
"four": 4,
"five": 5,
"six": 6,
"seven": 7,
"eight": 8,
"nine": 9,
}
TEENS = {
"ten": 10,
"eleven": 11,
"twelve": 12,
"thirteen": 13,
"fourteen": 14,
"fifteen": 15,
"sixteen": 16,
"seventeen": 17,
"eighteen": 18,
"ninteen": 19,
}
TENS = {
"twenty": 20,
"thirty": 30,
"fourty": 40,
"fifty": 50,
"sixty": 60,
"seventy": 70,
"eighty": 80,
"ninety": 90,
}
HUNDRED = "hundred"
DECIMALS = {
"thousand": 1_000,
"million": 1_000_000,
}
def from_words(words):
total = 0
hundreds_part = 0
state = 0
for word in words:
if state == 0:
if word in ONES:
hundreds_part = ONES[word]
state = 1
elif word in TEENS:
hundreds_part = TEENS[word]
state = 2
elif word in TENS:
hundreds_part = TENS[word]
state = 3
elif state == 1:
if word == HUNDRED:
hundreds_part *= 100
state = 4
elif word in DECIMALS:
hundreds_part *= DECIMALS[word]
total += hundreds_part
hundreds_part = 0
state = 0
elif state == 2:
if word in DECIMALS:
hundreds_part *= DECIMALS[word]
total += hundreds_part
hundreds_part = 0
state = 0
elif state == 3:
if word in ONES:
hundreds_part += ONES[word]
state = 5
elif word in DECIMALS:
hundreds_part *= DECIMALS[word]
total += hundreds_part
hundreds_part = 0
state = 0
elif state == 4:
if word in ONES:
hundreds_part += ONES[word]
state = 5
elif word in TEENS:
hundreds_part += TEENS[word]
state = 2
elif word in TENS:
hundreds_part += TENS[word]
state = 3
elif word in DECIMALS:
hundreds_part *= DECIMALS[word]
total += hundreds_part
hundreds_part = 0
state = 0
elif state == 5:
if word in DECIMALS:
hundreds_part *= DECIMALS[word]
total += hundreds_part
hundreds_part = 0
state = 0
total += hundreds_part
return total
if __name__ == "__main__":
# print from the list of inputs any phrases representing a multiple of 3
inputs = [
"five",
"twenty six",
"nine hundred ninety nine",
"twelve",
"eighteen",
"one hundred one",
"fifty two",
"forty one",
"seventy seven",
"six",
"twelve",
"four",
"sixteen",
# extra that I added myself, to show thousands and millions in action
"one hundred twenty three thousand four hundred fifty six",
"nine hundred ninety nine million one",
"nine hundred ninety nine million three"
]
for phrase in inputs:
words = phrase.split(" ")
if from_words(words) % 3 == 0:
print(phrase)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment