pythonlistdigits

Given a phone number in words, convert the number to digits


The below code work's fine for

Input: "two one nine six eight one six four six zero"

Output: "2196816460"
n=s.split()
    l=[]
    for val in n:
        if(val=='zero'):
            l.append('0')
        elif(val=='one'):
            l.append("1")
        elif(val=='two'):
            l.append("2")
        elif(val=='three'):
            l.append("3")
        elif(val=='four'):
            l.append("4")
        elif(val=="five"):
            l.append("5")
        elif(val=="six"):
            l.append("6")
        elif(val=="seven"):
            l.append("7")
        elif(val=="eight"):
            l.append("8")
        elif(val=="nine"):
            l.append("9")
    new = ''.join(l)
    return new

But what if,

Input: "five eight double two double two four eight five six"
Required Output should be : 5822224856
or,
Input: "five one zero six triple eight nine six four"
Required Output should be : 5106888964 How can the above code be modified?


Solution

  • Create another mapping for the quantity modifiers, and multiply the digit string by the preceding modifier.

    digits = {
        "zero": "0",
        "one": "1",
        "two": "2",
        "three": "3",
        "four": "4",
        "five": "5",
        "six": "6",
        "seven": "7",
        "eight": "8",
        "nine": "9",
    }
    
    modifiers = {
        "double": 2,
        "triple": 3,
    }
    
    number = ""
    n = 1
    for word in input("? ").split():
        if word in modifiers:
            n *= modifiers[word]
        else:
            number += n * digits[word]
            n = 1
    print(number)
    
    ? five eight double two double two four eight five six
    5822224856