четверг, 12 декабря 2013 г.

Python преобразование числа [0-999] в текст

Например преобразовать 310 => three hundred ten


Мое решение:

FIRST_TEN = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"]

SECOND_TEN = ["ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"]

OTHER_TENS = ["twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"]

HUNDRED = "hundred"

number = 310

res_n = ""
lst = list(str(number))

if len(lst) == 1:
    res_n = FIRST_TEN[int(lst[0])]
    
if len(lst) == 2:
    if int(lst[0]) == 1:
        res_n = SECOND_TEN[int(lst[1])]
    elif int(lst[0]) > 1:
        if int(lst[1]) == 0:
            res_n = OTHER_TENS[int(lst[0]) - 2]
        elif int(lst[1]) > 0:
            res_n = OTHER_TENS[int(lst[0]) - 2] + ' ' + FIRST_TEN[int(lst[1])]   

if len(lst) == 3:
    if int(lst[1]) == 0:
        if int(lst[2]) == 0:
            res_n = FIRST_TEN[int(lst[0])] + ' ' + HUNDRED
        elif int(lst[2]) > 0:
            res_n = FIRST_TEN[int(lst[0])] + ' ' + HUNDRED + ' ' + FIRST_TEN[int(lst[2])]
    elif int(lst[1]) == 1:
        res_n = FIRST_TEN[int(lst[0])] + ' ' + HUNDRED + ' ' + SECOND_TEN[int(lst[2])]
    elif int(lst[1]) > 1:
        if int(lst[2]) == 0:
            res_n = FIRST_TEN[int(lst[0])] + ' ' + HUNDRED + ' ' + OTHER_TENS[int(lst[1]) - 2]
        elif int(lst[2]) > 0:
            res_n = FIRST_TEN[int(lst[0])] + ' ' + HUNDRED + ' ' + OTHER_TENS[int(lst[1]) - 2] + ' ' + FIRST_TEN[int(lst[2])]

print res_n
three hundred ten
Решение от гуру:
def convert(i): if i < 20: result = 'zero,one,two,three,four,five,six,seven,eight,nine,ten,eleven,twelve,thirteen,fourteen,fifteen,sixteen,seventeen,eighteen,nineteen'.split(',')[i] elif i < 100: result = ',,twenty,thirty,forty,fifty,sixty,seventy,eighty,ninety'.split(',')[i//10] if i % 10: result += ' ' + checkio(i % 10) elif i < 1000: result = checkio(i // 100) + ' hundred' if i % 100: result += ' ' + checkio(i % 100) return result

Комментариев нет:

Отправить комментарий