-2

I have this list [5, '*', 10, '/', 22] and I want to write a function that it solve this math thing and return the answer but I have no idea about how I can do it ...

1

3 Answers 3

0

You can use eval but one should be cautious about it:

l=[5, '*', 10, '/', 22]
y=eval(''.join([str(x) for x in l]))
print(y)
4
  • but It's answer isn't correct (mathematically)
    – MossBat
    Jul 22, 2021 at 11:34
  • @MossBat, it correct. I just checked with the calculator
    – user15801675
    Jul 22, 2021 at 11:36
  • @PCM, what answer did you get?
    – user15801675
    Jul 22, 2021 at 12:02
  • Well, that is what, the calc shows. Actually, it is technically correct. But probably the division and multiplication got messed up in the eval
    – PCM
    Jul 22, 2021 at 12:05
0

First, create a string of this expression by using join function but make sure all the contents inside the list are of type <str>

l = [5, '*', 10, '/', 22]
l = [str(x) for x in l]
exp = ''.join(l)

Then use eval to evaluate the expression string

eval(exp)
1
-1

Or more advanced solution try to use Reverse Polish Notation

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.