转换三位以内的阿拉伯数字为英文
我的解法:(基本上也就是用笨办法if出来了……主要是//整除和%取余的应用)
FIRST_TEN = ["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 = ""
if number < 10:
result = FIRST_TEN[number-1]
elif number < 100:
if number < 20:
result = SECOND_TEN[number-10]
elif number%10 == 0:
result = OTHER_TENS[number//10-2]
else:
result = OTHER_TENS[number//10-2]+" "+FIRST_TEN[number%10-1]
else:
if number%100 in range(10,20):
result = FIRST_TEN[number//100-1]+" "+HUNDRED+" "+SECOND_TEN[number%10]
elif number%100 in range(1,10):
result = FIRST_TEN[number//100-1]+" "+HUNDRED+" "+FIRST_TEN[number%100-1]
elif number%100 == 0:
result = FIRST_TEN[number//100-1]+" "+HUNDRED
elif number%10 == 0:
result = FIRST_TEN[number//100-1]+" "+HUNDRED+" "+OTHER_TENS[number%100//10-2]
else:
result = FIRST_TEN[number//100-1]+" "+HUNDRED+" "+OTHER_TENS[number%100//10-2]+" "+FIRST_TEN[number%10-1]
return result
RANDOM SOLUTION
(真心惊艳!写法非常简练,涉及chain,zip,f-string用法,说实话还有点没看懂,保存下来慢慢学习!)
from itertools import chain
TWENTY = [
'', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight',
'nine', 'ten', 'eleven', 'twelve', 'thirteen','fourteen', 'fifteen',
'sixteen', 'seventeen', 'eighteen', 'nineteen'
]
TENS = ['twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety']
N = dict(chain(enumerate(TWENTY), zip(range(20, 91, 10), TENS)))
def checkio(n):
n, h, u = n % 100, n // 100, n % 10
return (f'{N[h]} hundred ' * (h>0) + N.get(n, f'{N[n-u]} {N[u]}')).strip()