题解 | #学英语#

学英语

http://www.nowcoder.com/practice/1364723563ab43c99f3d38b5abef83bc

num1 = ['zero', 'one', 'two', 'three', 'four', 'five', 'six',
        'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve',
        'thirteen', 'fourteen', 'fifteen', 'sixteen',
        'seventeen', 'eighteen', 'nineteen']
num2 = [0, 0, 'twenty', 'thirty', 'forty', 'fifty', 'sixty',
        'seventy', 'eighty', 'ninety']


def read2(n):
    """转换100以内的数"""
    res2 = []
    if n != 0:
        if n < 20:
            res2.append(num1[n])
        else:
            res2.append(num2[n // 10])
            if n % 10 != 0:
                res2.append(num1[n % 10])
    return res2


def read3(n):
    """转换1000以内的数"""
    res3 = []
    if n >= 100:
        res3 = [num1[n // 100], 'hundred']
        if n % 100 != 0:
            res3.append('and')
    res3 += read2(n % 100)
    return res3


while True:
    try:
        num = input()[::-1]
        res = ''
        lst = []
        for i in range(0, len(num), 3):
            lst.append(num[i:i + 3][::-1])
        num_lst = list(map(int, lst))
        if len(num_lst) == 1:
            res += ' '.join(str(word) for word in read3(num_lst[0]))
            print(res)
        elif len(num_lst) == 2:
            res += ' '.join(str(word) for word in read3(num_lst[1]))
            res += ' thousand '
            res += ' '.join(str(word) for word in read3(num_lst[0]))
            print(res)
        elif len(num_lst) == 3:
            res += ' '.join(str(word) for word in read3(num_lst[2]))
            res += ' million '
            res += ' '.join(str(word) for word in read3(num_lst[1]))
            res += ' thousand '
            res += ' '.join(str(word) for word in read3(num_lst[0]))
            print(res)
        elif len(num_lst) == 4:
            res += ' '.join(str(word) for word in read3(num_lst[3]))
            res += ' billion '
            res += ' '.join(str(word) for word in read3(num_lst[2]))
            res += ' million '
            res += ' '.join(str(word) for word in read3(num_lst[1]))
            res += ' thousand '
            res += ' '.join(str(word) for word in read3(num_lst[0]))
            print(res)
    except:
        break
全部评论

相关推荐

1 1 评论
分享
牛客网
牛客企业服务