不想冗余并且想使用递归

时间:2019-02-04 00:45:08

标签: python recursion redundancy

我正在使用Python 3.7,并希望编写用于拼写数字(很大或很小)的程序。我写了一些东西,但是问题是,如果我确实写这样的代码,那将是多余的并且时间太长。无论输入多大,是否可以通过其他方法打印拼写?例如,如果我输入659556009,我想得到一个输出,例如“六百五十九,五千五百六十九万”。或者,如果我给2001,它将给我2000。 谁能帮我吗?

num = int(input("number :"))

def word(num):
    d1= {0:'Zero',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',16:'Sixteen',17:'Seventeen',18:'Eighteen',19:'Ninteen',20:'Twenty',30:'Thirty',40:'Fourty',50:'Fifty',60:'Sixty',70:'Seventy',80:'Eighty',90:'Ninty'}
    k = 1000
    m = k * 1000
    if (num<20):
       return d1[num]
    if (num<100):
       if num % 10 == 0:
          return d1[num]
       else:
           return d1[num // 10 * 10] + ' ' + d1[num % 10]

    if (num < k):
        if num % 100 == 0:
           return d1[num // 100] + ' hundred'
        else:
            return d1[num // 100] + ' hundred ' + word(num % 100)
    if (num < m):
       if num % k == 0:
          return word(num // k) + ' thousand'
       else:
           return word(num // k) + ' thousand, ' + word(num % k)

print (word(num))

谢谢。

1 个答案:

答案 0 :(得分:0)

这是一个简单的手推递归数字文本转换器的方法:

from math import log

DIGITS = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']
TEENS = ['ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen']
TENS = ['error', 'error', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety']
POWERS = ['error', 'thousand', 'million', 'billion', 'trillion', 'quadrillion', 'quintrillion', 'sextillion', 'septillion', 'octillion', 'nonillion']

def three_digits_to_list(number):
    places = []

    while number:
        places.insert(0, number % 10)
        number //= 10

    result = []

    if len(places) == 3:
        result.extend([DIGITS[places.pop(0)], "hundred"])

    if len(places) == 2:
        if places[0] > 1:
            result.append(TENS[places.pop(0)])
        elif places[0] == 1:
            places.pop(0)
            result.append(TEENS[places.pop(0)])

    if len(places) == 1:
        result.append(DIGITS[places.pop(0)])

    return result

def number_to_list(number, flag=False):
    try:
        power = int(log(number, 1000))
    except ValueError:
        return [0] if flag else []  # special case for 0

    if power == 0:
        return three_digits_to_list(number)

    magnitude = 1000 ** power
    hundreds = number // magnitude

    return three_digits_to_list(hundreds) + [POWERS[power]] + number_to_list(number - hundreds * magnitude)

def number_to_text(number):
    return " ".join(number_to_list(number, True))

print(repr(number_to_text(659556009)))

输出:

> python3 test.py
'six hundred fifty nine million five hundred fifty six thousand nine'
>

我确定仍有一些特殊情况需要处理,但这是OP的一项练习。