|
发表于 2020-2-15 21:15:25
|
显示全部楼层
本帖最后由 Windypper 于 2020-2-15 21:23 编辑
- # !/usr/bin/env python
- # -*- coding: utf-8 -*-
- def input_num():
- try:
- num = int(input('Please input a positive integer: '))
- if num < 1e15:
- return num
- else:
- print('Integer must be less than 1E+15 and greater than 0')
- input_num()
- except ValueError:
- print('Input Error\n\n')
- input_num()
- cardinal = {0: '', 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',
- }
- thousands = {1: '', 2: 'Thousand', 3: 'Million', 4: 'Billion', 5: 'Trillion'}
- def num_eng(num, loop=0):
- num_text = ''
- loop += 1
- if num:
- tens = num % 100 # extract tens digit and unit digit
- if tens <= 20: # the situation tens number less than 20
- tens_text = cardinal[tens]
- else: # the situation tens number greater than 20
- ten_digit = cardinal[tens - tens % 10] # extract tens digit
- unit_digit = cardinal[tens % 10] # extract unit digit
- if ten_digit and unit_digit: # if both tens digit and unit digit are non-zero, add a hyphen between
- tens_text = f"{ten_digit}-{unit_digit}"
- else:
- tens_text = f"{ten_digit}{unit_digit}"
- if tens and loop > 1: # if the number is greater than one thousand, add a space after unit digit
- tens_text += ' '
- hundreds = num // 100 % 10 # extract hundred digit
- if not hundreds: # if hundreds digit is zero, add nothing to the string
- hundreds_text = ''
- else:
- hundreds_text = f'{cardinal[hundreds]} hundred '
- # make string to be titlecased
- tens_text = tens_text.title()
- hundreds_text = hundreds_text.title()
- # add 'and' before tens digit in two situations:
- # 1. both tens digit and hundreds digits are non-zero
- # 2. the last tens digit when the number is greater than one thousand
- if tens and hundreds or num // 1000 and tens and loop == 1:
- hundreds_text += 'and '
- # add 'and' before hundreds digit if it is the last one
- if num // 1000 and hundreds and not tens and loop == 1:
- hundreds_text = 'and ' + hundreds_text
- # recurse to higher magnitude
- num_text = num_eng(num // 1000, loop)
- return num_text + hundreds_text + tens_text + thousands[loop] + ' '
- else:
- if loop == 1:
- num_text = 'Zero'
- return num_text
- if __name__ == '__main__':
- num = input_num()
- print(num_eng(num))
复制代码
不是應該加上and嗎
試了下我這個好像沒問題 |
评分
-
查看全部评分
|