[Python] 遞迴解 number digital into number pronunciation

摘要:[Python] 遞迴解 number digital into number pronunciation

最近在checkio上面磨練自己的程式功力,發現好多高手程式設計的思維讓人望塵莫及。

以下是要解的題目是將數字轉換為英文數字的單字字串:

Input: Integer number from 0 to 999.
Output: A string representation of this number.
Result:
checkio(4)=='four'
checkio(143)=='one hundred forty three'
checkio(12)=='twelve'
checkio(101)=='one hundred one'
checkio(212)=='two hundred twelve'
checkio(40)=='forty'

 

我的解法很直觀,直接對位數拆解,大多數的人也是依照這種想法來解:

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"

def checkio(number):
    result = []
    f = lambda x, y: (x/y, x%y)
    for i in [2, 1, 0]:
        quotient, remainder = f(number, 10**i)
        if i == 2:
            if quotient > 0:
                result += [FIRST_TEN[quotient], HUNDRED]
                if remainder == 0:
                    break                
            number = remainder
        if i == 1:
            if quotient >= 2:
                result += [OTHER_TENS[quotient-2]]
                if remainder == 0:
                    break
                number = remainder
        if i == 0:
            if quotient >= 10 and quotient < 20:
                result += [SECOND_TEN[quotient-10]]
                break
            elif quotient < 10:
                result += [FIRST_TEN[quotient]]
    return ' '.join(result)

以下是遞迴解 - 這需要花點力氣來看懂,更遑論要想到這樣的解法,以前教授也有提過大部分的programmer都不擅長用遞迴來解題,主要是因為在演算法的邏輯上大多不太直觀。

def checkio(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