Skip to content

Instantly share code, notes, and snippets.

@PetrGlad
Created May 4, 2024 16:24
Show Gist options
  • Save PetrGlad/350d98d5b7a6a59dab2f77ceb1203e08 to your computer and use it in GitHub Desktop.
Save PetrGlad/350d98d5b7a6a59dab2f77ceb1203e08 to your computer and use it in GitHub Desktop.
An exersice problem
import sys
DIGITS = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']
TEENS = ['ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen']
TENS = ['ten', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety']
def speek_0(n: int) -> [str]:
"""Auxiliary function."""
words = []
if n == 0:
return [DIGITS[0]]
assert n < 1_000_000
if 1000 <= n:
thousands = n // 1_000
words += speek_0(thousands) + ["thousand"]
n %= 1000
assert n < 1000
if 100 <= n:
hundreds = n // 100 % 10
words += [DIGITS[hundreds], "hundred"]
n %= 100
assert n < 100;
if 10 <= n < 20:
words += [TEENS[n - 10]]
else:
if 20 <= n < 100:
words += [TENS[n // 10 - 1]]
n %= 10
if 0 < n < 10:
words += [DIGITS[n]]
return words
def speek_v1(digits: str) -> str:
"""Number to speech using numerals up to thousands."""
return " ".join(speek_0(int(digits)))
def speek_1(n: [int]) -> [str]:
# ???
pass
def speek_v2(digits: str) -> str:
return " ".join(speek_1(list(digits)))
TESTCASES = {
'0': "zero",
'1': "one",
'10': "ten",
'15': "fifteen",
'20': "twenty",
'35': "thirty five",
'100': "one hundred",
'103': "one hundred three",
'147': "one hundred forty seven",
'9452': "nine thousand four hundred fifty two",
'641384': "six hundred forty one thousand three hundred eighty four",
# '32641384': "thirty two thousand six hundred forty one thousand three hundred eighty four"
}
def test(fn):
print('-' * 10, "TESTING", fn.__name__)
for number, words in TESTCASES.items():
actual = fn(number)
print(f"{number} -> {words} : {actual}")
sys.stdout.flush()
if not actual == words:
print(f" FAILED : actual {actual}, expected {words}")
return
print(" OK ")
test(speek_v1)
test(speek_v2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment