Python Forum
Evaluating math from left to right in coding
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Evaluating math from left to right in coding
#1
problem = int(eval(input('Enter a math problem')))
print(problem)
When using the code I have above it does evaluate the problem however it only does so using the PEMDAS rules. Is there a way I can make it evaluate from left to right no matter what the signs are?
buran write Mar-23-2021, 05:38 PM:
Please, use proper tags when post code, traceback, output, etc. This time I have added tags for you.
See BBcode help for more info.
Reply
#2
If this is homework, wouldn't the homework part be figuring out how to evaluate the equation? Splitting the equation into tokens, identifying which tokens are operators and which are numbers. Evaluating the equation starting with the first token and ending with the last. An interesting, but not not terribly difficult challenge.
Reply
#3
(Mar-23-2021, 05:49 PM)deanhystad Wrote: If this is homework, wouldn't the homework part be figuring out how to evaluate the equation? Splitting the equation into tokens, identifying which tokens are operators and which are numbers. Evaluating the equation starting with the first token and ending with the last. An interesting, but not not terribly difficult challenge.

I am only a beginner with python and I read through my textbook entirely and I can't find anything about being able to evaluate left to right. I didn't know if there was a specific function to be used or how to even approach this.
Reply
#4
I do not think there is a function. I think you have to do something like this.

User input = '3 + 4'

You split this into tokens, substrings that are separated by spaces ['3', '+', '4']

Starting with the first token you determine if it is a number or an operator and take the appropriate action.

'3' is a number. Convert to 3
'+' is the addition operator. Do something to remember this
'4' is a number. Convert to 4
Do addition, 3 + 4 = 7
Print out result

Most of your programming class is solving puzzles. Very seldom is there a "thing being able" to do any of the problems you are assigned. You have to solve the puzzle using your brain, then convert the solution from your head into programming language code.

If you were sitting down with a pencil and paper, and were told you could only look at a few characters at a time, how would you solve '3 + 4'. Develop a scheme that works for different operators and maybe equations with multiple operators (I don't know the details of your assignment). Once you have a detailed plan in your head, then start thinking about how you can do that plan using Python.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Cross-validation: evaluating estimator performance Grin 1 2,648 Jun-29-2018, 05:15 AM
Last Post: scidam

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020