题目
In this kata we want to convert a string into an integer. The strings simply represent the numbers in words.
Examples:
- "one" => 1
- "twenty" => 20
- "two hundred forty-six" => 246
- "seven hundred eighty-three thousand nine hundred and nineteen" => 783919
Additional Notes:
- The minimum number is "zero" (inclusively)
- The maximum number, which must be supported is 1 million (inclusively)
- The "and" in e.g. "one hundred and twenty-four" is optional, in some cases it's present and in others it's not
- All tested numbers are valid, you don't need to validate them
我的答案
dic = {'zero':0, 'one':1, 'two':2, 'three':3, 'four':4, 'five':5, 'six':6, 'seven':7, 'eight':8, 'nine':9, 'ten':10, 'eleven':11, 'twelve':12, 'thirteen':13, 'fourteen':14, 'fifteen':15, 'sixteen':16, 'seventeen':17, 'eighteen':18, 'nineteen':19, 'twenty':20, 'thirty':30, 'forty':40, 'fifty':50, 'sixty':60, 'seventy':70, 'eighty':80, 'ninety':90}
import re
def parse_int(string):
if not string:
return 0
else:
string = string.strip()
l = [i for i in re.split('[\s\-]', string.strip()) if i]
if len(l) == 1:
return dic[string]
elif 'million' in string:
p = string.split('million')
return 1000000*parse_int(p[0]) + parse_int(p[1])
elif 'thousand' in string:
p = string.split('thousand')
return 1000*parse_int(p[0]) + parse_int(p[1])
elif 'hundred' in string:
p = string.split('hundred')
return 100*parse_int(p[0]) + parse_int(p[1])
else:
string = re.sub('and', '', string.strip())
l = [i for i in re.split('[\s\-]', string) if i]
return dic[l[0]] if len(l) == 1 else dic[l[0]] + dic[l[1]]
其他精彩答案
words = {w: n for n, w in enumerate('zero one two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen'.split())}
words.update({w: 10 * n for n, w in enumerate('twenty thirty forty fifty sixty seventy eighty ninety hundred'.split(), 2)})
thousands = {w: 1000 ** n for n, w in enumerate('thousand million billion trillion quadrillion quintillion sextillion septillion octillion nonillion decillion'.split(), 1)}
def parse_int(strng):
num = group = 0
for w in strng.replace(' and ', ' ').replace('-', ' ').split():
if w == 'hundred': group *= words[w]
elif w in words: group += words[w]
else:
num += group * thousands[w]
group = 0
return num + group