-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathevaluate_expression.py
93 lines (88 loc) · 2.1 KB
/
evaluate_expression.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
# -----------------------------------------------
# Author : Mohit Chaudhari
# Created Date : 08/09/21
# -----------------------------------------------
# ***** Evaluate Expression *****
# Problem Description
#
# An arithmetic expression is given by a charater array A of size N. Evaluate the value of an arithmetic expression in Reverse Polish Notation.
#
# Valid operators are +, -, *, /. Each character may be an integer or an operator.
#
#
#
# Problem Constraints
# 1 <= N <= 105
#
#
#
# Input Format
# The only argument given is character array A.
#
#
#
# Output Format
# Return the value of arithmetic expression formed using reverse Polish Notation.
#
#
#
# Example Input
# Input 1:
# A = ["2", "1", "+", "3", "*"]
# Input 2:
# A = ["4", "13", "5", "/", "+"]
#
#
# Example Output
# Output 1:
# 9
# Output 2:
# 6
#
#
# Example Explanation
# Explaination 1:
# starting from backside:
# * : () * ()
# 3 : () * (3)
# + : (() + ()) * (3)
# 1 : (() + (1)) * (3)
# 2 : ((2) + (1)) * (3)
# ((2) + (1)) * (3) = 9
# Explaination 2:
# + : () + ()
# / : () + (() / ())
# 5 : () + (() / (5))
# 1 : () + ((13) / (5))
# 4 : (4) + ((13) / (5))
# (4) + ((13) / (5)) = 6
class Solution:
# @param A : list of strings
# @return an integer
def evalRPN(self, A):
ln = len(A)
arr = list()
for i in range(ln):
if A[i] == "+":
b = arr.pop()
a = arr.pop()
arr.append(int(b) + int(a))
elif A[i] == "-":
b = arr.pop()
a = arr.pop()
arr.append(int(a) - int(b))
elif A[i] == "/":
b = arr.pop()
a = arr.pop()
arr.append(int(a) // int(b))
elif A[i] == "*":
b = arr.pop()
a = arr.pop()
arr.append(int(b) * int(a))
else:
arr.append(int(A[i]))
return arr.pop()
s = Solution()
print(s.evalRPN(["4", "13", "5", "/", "+"]))
# print(s.evalRPN(["2", "1", "+", "3", "*"]))
# OUTPUT: 9