Xrin Xrin - 20 days ago 7
Python Question

Reverse Polish Expression - Monitoring the Input

So I have the code to make the Reverse Polish Expression work

def rpn(x):
stack = []
operators=['+', '-', '*']

for i in x.split(' '):
if i in operators:
op1 = stack.pop()
op2 = stack.pop()
if i=='+': result = op2 + op1
if i=='-': result = op2 - op1
if i=='*': result = op2 * op1
stack.append(result)
else:
stack.append(float(i))

return stack.pop()


x = str(input("Enter a polish expression:"))
result = rpn(x)
print (result)


However I'm struggling on how to provide some error messages for specific inputs
Currently this code will only work if i have a space after each value i.e.
3 4 + then ill get a result of 7

But I want to make it so that it either

-Removes the spacing automatically

or the code will only work without the spacing and provide an error if there is spacing
I thought of adding the code something along the lines of

if x contains " ":
print("error")


My second issue that i'm trying to work around is, limiting the operators used
So it will only run the code if it has numbers and 3 operators (+,-,*) if there are any other operators or letters it will show an error. Again my thinking of it would be

if x contains something other than "integers and +,-,*:
then print an error


Again I have the concept but not the python key word knowledge on how to perform it.

Answer

You should use x.split() instead of x.split(' '), it will extract everything but the spaces from x.

split() treats multiple successive spaces as one space (so one delimiter), while split(' ') treats one space as one delimiter.

Here's the difference:

>>> print('   '.split(' '))
['', '', '', '']
>>> print('   '.split())
[]

Given that your code will be dealing only with single-digit numbers:

for i in (_ for _ in x if not _.isspace()):
    # your algorithm

If you'd like to raise an error:

for i in (_ if not _.isspace() else None for _ in x):
    if i is None:
        raise ValueError("Error!")
    # your algorithm here
Comments