首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python转换器:数字到英语- Project Euler 17

Python转换器:数字到英语- Project Euler 17
EN

Code Review用户
提问于 2014-01-13 21:24:35
回答 1查看 2.4K关注 0票数 4

因此,我编写了这个函数,将给定的数字转换为英语中的解释,作为欧拉项目练习的一部分。它工作得很好,但我感觉到它相当草率和不雅,特别是对于Python来说,很多事情可以在几行代码中快速完成。任何反馈意见,如何使这个代码更美丽/毕多尼感谢!

代码语言:javascript
复制
NUMBER_WORDS = {
    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 : "nineteen",
    20 : "twenty",
    30 : "thirty",
    40 : "forty",
    50 : "fifty",
    60 : "sixty",
    70 : "seventy",
    80 : "eighty",
    90 : "ninety"
}

def convert_number_to_words(num):
    #Works up to 99,999
    num = str(num)
    analyze = 0
    postfix = remainder = None
    string = ""
    if len(num) > 4:
        analyze = int(num[0:2])
        remainder = num[2:]
        postfix = " thousand "
    elif len(num) > 3:
        analyze = int(num[0:1])
        remainder = num[1:]
        postfix = " thousand "
    elif len(num) > 2:
        analyze = int(num[0:1])
        remainder = num[1:]
        postfix = " hundred "
        if int(remainder) > 0:
            postfix += "and "
    elif int(num) in NUMBER_WORDS:
        analyze = int(num)
    else:
        analyze = int(num[0:1] + "0")
        remainder = num[1:]
        postfix = "-"
    string = NUMBER_WORDS[analyze]
    if postfix is not None:
        string += postfix
    if remainder is not None and int(remainder) > 0:
        return string + convert_number_to_words(remainder)
    else:
        return string
EN

回答 1

Code Review用户

回答已采纳

发布于 2014-01-14 06:03:08

这里有一个使用模块化%和列表连接的方法,它使用了原始的NUMBER_WORDS dict:

代码语言:javascript
复制
def int_to_english(n):
    english_parts = []
    ones = n % 10
    tens = n % 100
    hundreds = math.floor(n / 100) % 10
    thousands = math.floor(n / 1000)

    if thousands:
        english_parts.append(int_to_english(thousands))
        english_parts.append('thousand')
        if not hundreds and tens:
            english_parts.append('and')
    if hundreds:
        english_parts.append(NUMBER_WORDS[hundreds])
        english_parts.append('hundred')
        if tens:
            english_parts.append('and')
    if tens:
        if tens < 20 or ones == 0:
            english_parts.append(NUMBER_WORDS[tens])
        else:
            english_parts.append(NUMBER_WORDS[tens - ones])
            english_parts.append(NUMBER_WORDS[ones])
    return ' '.join(english_parts)

它可以达到999,999,但只要稍加定制,就可以进一步扩展。

票数 4
EN
页面原文内容由Code Review提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://codereview.stackexchange.com/questions/39183

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档