-2

New to python here. I am working on a problem to write a script that gets user input in the form of a word problem such as “two plus three” and “seven minus five”, but returns a numerical value as the output. For example, if the user enters "two plus three" the output should be 5 (assuming the user only enters numbers 0-9 and operations plus, minus, times, and divided by).

I'm thinking I need to break apart the string into the numbers and the operation. Should I use .split? And how do I get the spelled-out number to process as a numerical value?

smugthug
  • 3
  • 2
  • 1
    In order for someone to help you on here you want to show what you've already tried, some sample input and expected output. You mentioned `split`, what happened when you tried that? That should be a good place to start. Then that leaves going from words to integers, I would recommend a dictionary if you're only supporting 0-9 – sedavidw Dec 10 '19 at 04:08
  • you should use dictionary. keep a (key,value) pair data-structure of (word, numeric value of that word) and also (operator name, operator). then you can just look up the dictionary for corresponding numeric value for a word and do the operation. – Arnab Roy Dec 10 '19 at 04:08
  • see also : https://stackoverflow.com/questions/493174/is-there-a-way-to-convert-number-words-to-integers – Joran Beasley Dec 10 '19 at 04:09
  • @sedavidw I did explain what the input and output should be. Like I said, I'm new to python, so try to be a little understanding. We all have to start somewhere :) – smugthug Dec 11 '19 at 19:45
  • @smugthug absolutely we all have to understand somewhere. What I meant by input and output is the **CODE** input you've tried and what was the output fo that code. You've given some test cases which is good but you'll find contributors more helpful when you've shown you made an attempt and you have targeted questions – sedavidw Dec 11 '19 at 20:27

1 Answers1

0

We can turn the string into the equivalent numbers and operators in python and then evaluate that expression to get the answer. For example we turn "two plus three" into "2+3" and then evaluate that using eval

words_to_symbols = {
    'one': '1',
    'two': '2',
    'three': '3',
    'four': '4',
    'five': '5',
    'six': '6',
    'seven': '7',
    'eight': '8',
    'nine': '9',
    'plus': '+',
    'minus': '-',
    'times': '*',
    'divide': '/'
}

def parse_and_eval(string):
    # Turn words into the equivalent formula
    operation = ''.join(words_to_symbols[word] for word in string.split())
    return eval(operation)

parse_and_eval('two plus three')  # returns 5
Iain Shelvington
  • 31,030
  • 3
  • 31
  • 50