This is the reason I wrote this article, but at the university test
For the problem. I took a lot of time in one part, so I made it for my own memo.
RPN.py
def isnum():
if int(hoge) == True:
return 1
else:
return 0
def cal(operand,a,b):
if operand == "+":
return int(a)+int(b)
elif operand == "-":
return int(a)-int(b)
elif operand == "*":
return int(a)*int(b)
por=[]
por = list(input().split())
stk=[]
for i in por:
if isnum(i) == int:
#It was a hassle here
stk.append(int(i))
else:
b=stk.pop()
a=stk.pop()
stk.append(cal(i,a,b))
print(stk[0])
Input example.txt
1 2 * 3 +
1 2 3 4 - * 5 - +
During the test, I couldn't think of a method well, so I couldn't look it up. I was stuck in the comment above.
In Reverse Polish Notation, operands and numbers are included. In other words, it is necessary to determine whether it is a character or an operand. In the ʻisnum` function above, it is necessary to determine whether the incoming character is an int type number or a character type operand.
I couldn't implement the part of whether a string can be cast to a number here, and I couldn't program it after all.
It seems that everything can be solved by using ʻisdigit ()`. If you use isdigit (), it will return whether it can be converted to an int type.
isdigittest.py
word=["1","hato","1.0",""]
for w in word:
print(w + " -> ",end="")
print(w.isdigit())
output
out.txt
1 -> True
hato -> False
1.0 -> True
-> False
It will determine if you can cast a string to an integer type like this. You can do anything with this.
If you actually use this and rewrite the above code, it will look like this.
RPN2.py
def cal(operand,a,b):
if operand == "+":
return int(a)+int(b)
elif operand == "-":
return int(a)-int(b)
elif operand == "*":
return int(a)*int(b)
por=[]
por = list(input().split())
stk=[]
for i in por:
if i.isdigit() == True:
stk.append(int(i))
else:
b=stk.pop()
a=stk.pop()
stk.append(cal(i,a,b))
print(stk[0])
isnum.py
def isnum():
if int(hoge) == True:
return 1
else:
return 0
I don't need this part in the first place. If you use isdigit (), you don't need this function. After all, I became a one-liner. When I ran the above program, I was able to get the correct answer.
Answer.txt
5
-6
Recommended Posts