-2

I'm trying to make a python calculator that takes inputs like these:

>>> 2+2*3

or

>>> 3*45+2*52/3

or

>>> 1+21/7-14/2

And return their answers with order of operations in mind. I am not allowed to use any modules and I get user inputs in one line, one string. And basically there is no limit on how many operations user can enter.

I tried to strip away my operators and numbers like this:

userin=input()
operators=[]

numbers=userin.replace('+',' ').replace('-',' ').replace('*',' ').replace('/',' ').split()
for char in userin:
    if char=='+' or char=='-' or char=='*' or char=='/':
        operators.append(char)

But my brain has stopped after trying to do basic math with order of operations this weekend. Any help?

labalumba
  • 43
  • 7
  • 2
    Can you use `eval` ? – madprops May 08 '22 at 21:39
  • You don't appear to have tried doing any kind of math at all. – Scott Hunter May 08 '22 at 21:41
  • You could use [the shunting yard algorithm](https://en.wikipedia.org/wiki/Shunting_yard_algorithm), for example. Note that coding such a calculator isn't trivial, so you probably won't be able to come up with a correct algorithm on your first try. – ForceBru May 08 '22 at 21:42
  • you will have to write an expression parser for that – Shantanu Aryan May 08 '22 at 21:42
  • That's not the right way to do this. You have to scan the string one character at a time. As long as you get digits, you build up a number (`accum = accum * 10 + int(newdigit)`). If it's not a digit, you have to use a stack to hold numbers and operators until you know it's safe to do an operation. – Tim Roberts May 08 '22 at 22:20
  • Do you consider the question answered, or do you need a way to do it without imports and builtins that do this? – Nin17 May 11 '22 at 05:34

1 Answers1

0

Python has calculator built-in, check out

exec(f"print({input()})")

Calculator in python - Colab

Anytokin
  • 117
  • 5