Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

converting string mathematical instruction into its equivalent operation

i want to convert a string mathematical instruction into it’s equivalent integer operation;

eg:
1.’double three’= 33

  1. ‘triple six’=666

my code is:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

hashmap={
'one': '1',
'two': '2',
'three': '3',
'four': '4',
'five': '5',
'six': '6',
'seven': '7',
'eight': '8',
'nine': '9',
'zero' : '0'}


str1="one five three"
st2int = ''.join(hashmap[ele] for ele in str1.split())
print(st2int)

my program is only for the str numbers to integer..
how can i make it to work for instruction like double,triple,quadrapleetc as i mentioned in the example

>Solution :

You make a separate dict for multipliers and for digits. If a word is in the multipliers dictionary, remember what its multiplier value is. If it’s in the digits dictionary, multiply by the current multiplier.

multipliers = {
    'double': 2,
    'triple': 3,
    'quadruple': 4
}
digits = {
    'one': '1',
    'two': '2',
    'three': '3',
    'four': '4',
    'five': '5',
    'six': '6',
    'seven': '7',
    'eight': '8',
    'nine': '9',
    'zero' : '0'
}

inputs = [ "one five three", "triple six", "double two", "triple double nine" ]
for i in inputs:
    multiplier = 1
    numbers = []
    for word in i.split():
        if word in multipliers:
            multiplier = multiplier * multipliers[word]
        if word in digits:
            numbers.append(multiplier * digits[word])
            multiplier = 1
    print(''.join(numbers))

This prints:

153
666
22
999999
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading