DEV Community

Discussion on: Daily Challenge #19 - Turn numbers into words

Collapse
 
_morgan_adams_ profile image
morgana • Edited

I tried to not dictionary everything, but the exceptions are real. Lots of amusing output as I got closer, that I'll paste for your enjoyment. I did actually get it working though :P

#15
fiveteen

# 818
eight hundred eightteen eight

# 101
one hundred oneteen one

# 654
six hundred six hundred six hundred
#!/usr/bin/env python

# 0 < num < 1000

num_map = {
        '1': 'one',
        '2': 'two',
        '3': 'three',
        '4': 'four',
        '5': 'five',
        '6': 'six',
        '7': 'seven',
        '8': 'eight',
        '9': 'nine',
        '10': 'ten',
        '11': 'eleven',
        '12': 'twelve',
        '13': 'thirteen',
        '14': 'fourteen',
        '15': 'fifteen',
        '18': 'eighteen',
        '20': 'twenty',
        '30': 'thirty',
        '50': 'fifty',
        '80': 'eighty'
}

num = input("Enter a number: ").lstrip('0')
inum = int(num)
word = ''

for _ in range(len(num)):
    if num in num_map:
        word = f'{word} {num_map[num]}'
        break
    elif inum < 20:
        lsi = num[1]
        word = f'{word} {num_map[lsi]}teen'
        break
    elif inum < 100:
        tendigit = num[0]
        tenword = f'{tendigit}0'
        if f'{tenword}' in num_map:
            word = f'{word} {num_map[tenword]}'
        else:
            word = f'{word} {num_map[tendigit]}ty'
    elif inum < 1000:
        hdigit = num[0]
        word = f'{word} {num_map[hdigit]} hundred'
    num = num[1:].lstrip('0')
    inum = int(num)

print(word.strip())