i want to convert a string mathematical instruction into it's equivalent integer operation;
eg: 1.'double three'= 33
- 'triple six'=666
my code is:
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,quadraple
etc as i mentioned in the example
CodePudding user response:
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