Home > Back-end >  Given a phone number in words, convert the number to digits
Given a phone number in words, convert the number to digits

Time:05-02

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?

CodePudding user response:

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

CodePudding user response:

You could use a variable to hold the repetitions of the next number.

The variable starts with value 1.

When get a repetition word ('triple') , then update the variable correspondingly.

When get a number ('three'), add to the list and update the variable back to 1

Also instead of using else..if you can use a dictionary:

repeat = 1
repeat_dict = {'double':2, 'triple':3}:

n=s.split()
l=[]
for val in n:
    if val in repeat_dict:   # got a repeat word
        repeat = repeat_dict[val]
    else:
          
        if(val=='zero'):
            l.append('0' * repeat) 
        elif(val=='one'):
            l.append("1" * repeat)
        elif(val=='two'):
            l.append("2" * repeat)
        elif(val=='three'):
            l.append("3" * repeat)
        elif(val=='four'):
            l.append("4" * repeat)
        elif(val=="five"):
            l.append("5" * repeat)
        elif(val=="six"):
            l.append("6" * repeat)
        elif(val=="seven"):
            l.append("7" * repeat)
        elif(val=="eight"):
            l.append("8" * repeat)
        elif(val=="nine"):
            l.append("9" * repeat)
        repeat = 1
new = ''.join(l)
return new
  • Related