0

Problem to solve: Write a script that enables the user to enter mathematical word problems like “What is two times three” and “What is seven minus five”, then use string processing to break apart the string into the numbers and the operation and return the result. So “two times three” would return 6 and “seven minus five” would return 2. To keep things simple, assume the user enters only the words for the numbers 0 through 9 and only the operations 'plus', 'minus', 'times' and 'divided by'.

Code written so far:

import operator
numbers = {'zero':0,'one':1,'two':2, 'three':3, 'four':4, 'five':5, 'six':6, 'seven':7, 
   'eight':8,'nine':9, 'plus': operator.add, 'minus': operator.sub, 'times': operator.mul, 
   'divided by':operator.truediv}
word_problem=(input('Type your word problem in this format: "What is two times three" ' ))
beginning_problem, seperator, new_problem=word_problem.rpartition('what is ')
result = new_problem.split()
result=tuple((result))
print(result)
print(numbers.get(result))

This allows me to input the question and prints a tuple of the relevant words (two times three) but then only prints "none"

1 Answers1

0

welcome!

Your code has some flaws:

beginning_problem, seperator, new_problem=word_problem.rpartition('what is ')

the above line is not working properly (it will only work for "what is..." but your own example is using "What is..." (capital w). To work with both, I suggest you use lower().

beginning_problem, seperator, new_problem=word_problem.lower().rpartition('what is ')

result = new_problem.split()

result is a list, and numbers.get is expecting a key (an immutable value). In your case, I think you need to pass every element of the result list.

for element in result:
  print(numbers.get(element))

You can also use numbers[key] instead of numbers.get(key). Se the differences here. Below is an example:

for element in result:
  print(numbers.get(element))

Just for clarification:a tuple is also an immutable value and can be used as a key for dicts, for instance:

numbers = {(2,3): "2 and 3"}

However, I think it is not what you are trying to do.

Good luck with your project!

  • This solved my initial issue! Thanks so much! It did create a new one though. It appears my dictionary is not quite right to get an actual solution to the math problem entered. Since I am unable to create a dictionary that has {'plus' : +, minus : -}, etc. What am I missing here? – lavender_frog Sep 11 '22 at 01:38
  • You can use operator.add or operator.sub as you did in your example. For instance: let's suppose your result is ['two', '+', 'two'], you will map it to [2, operator.add, 2]. A good way to do this is using list comprehensions, for instance: mapped = [numbers.get(key) for key in result]. Then you just return mapped[1](mapped[0], mapped[2]). – julianofischer Sep 11 '22 at 02:24