每日kata~11~parseInt() reloaded

题目

parseInt() reloaded
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

笨蛋解法

from enum import Enum
def parse_int(string):
    st = string.split(' ')
    b = []
    res = 0
    for i in st:
        if i!='hundred' and i!='thousand' and i!='and' and i!='million':
            b.append(parse_str(i))
        elif i=='hundred':
            s = b.pop()
            b.append(s*100)
        elif i=='thousand':
            s = 0
            while(b):
                s += b.pop()
            b.append(s*1000)
        elif i=='million':
            s = 0
            while(b):
                s += b.pop()
            b.append(s*1000000)
    for k in b:
        #print(k)
        res += k
        print(res)
    return res

def parse_str(st):
    num = 0
    if '-' in st:
        a = st.split('-')
        for i in a:
            num += number[i].value
    else:
        num = number[st].value
        
    return num

class number(Enum):
    zero = 0
    one = 1
    two = 2
    three = 3
    four = 4
    five = 5
    six = 6
    seven = 7
    eight = 8
    nine = 9
    ten = 10
    twenty = 20
    thirty = 30
    fourty = 40
    forty = 40
    fifty = 50
    sixty = 60
    seventy = 70
    eighty = 80
    ninety = 90
    eleven = 11
    twelve = 12
    thirteen = 13
    fourteen = 14
    forteen = 14
    fifteen = 15
    sixteen = 16
    seventeen = 17
    eighteen = 18
    nineteen = 19

高级解法

ONES = ['zero', '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']

def parse_int(string):
    print(string)
    numbers = []
    for token in string.replace('-', ' ').split(' '):
        if token in ONES:
            numbers.append(ONES.index(token))
        elif token in TENS:
            numbers.append((TENS.index(token) + 2) * 10)
        elif token == 'hundred':
            numbers[-1] *= 100
        elif token == 'thousand':
            numbers = [x * 1000 for x in numbers]
        elif token == 'million':
            numbers = [x * 1000000 for x in numbers]
    return sum(numbers)

你可能感兴趣的:(每日kata~11~parseInt() reloaded)