MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / evaluate

Function evaluate

data_structures/stacks/postfix_evaluation.py:64–187  ·  view source on GitHub ↗

Evaluate postfix expression using a stack. >>> evaluate(["0"]) 0.0 >>> evaluate(["-0"]) -0.0 >>> evaluate(["1"]) 1.0 >>> evaluate(["-1"]) -1.0 >>> evaluate(["-1.1"]) -1.1 >>> evaluate(["2", "1", "+", "3", "*"]) 9.0 >>> evaluate(["2", "1.9", "+

(post_fix: list[str], verbose: bool = False)

Source from the content-addressed store, hash-verified

62
63
64def evaluate(post_fix: list[str], verbose: bool = False) -> float:
65 """
66 Evaluate postfix expression using a stack.
67 >>> evaluate(["0"])
68 0.0
69 >>> evaluate(["-0"])
70 -0.0
71 >>> evaluate(["1"])
72 1.0
73 >>> evaluate(["-1"])
74 -1.0
75 >>> evaluate(["-1.1"])
76 -1.1
77 >>> evaluate(["2", "1", "+", "3", "*"])
78 9.0
79 >>> evaluate(["2", "1.9", "+", "3", "*"])
80 11.7
81 >>> evaluate(["2", "-1.9", "+", "3", "*"])
82 0.30000000000000027
83 >>> evaluate(["4", "13", "5", "/", "+"])
84 6.6
85 >>> evaluate(["2", "-", "3", "+"])
86 1.0
87 >>> evaluate(["-4", "5", "*", "6", "-"])
88 -26.0
89 >>> evaluate([])
90 0
91 >>> evaluate(["4", "-", "6", "7", "/", "9", "8"])
92 Traceback (most recent call last):
93 ...
94 ArithmeticError: Input is not a valid postfix expression
95
96 Parameters
97 ----------
98 post_fix:
99 The postfix expression is tokenized into operators and operands and stored
100 as a Python list
101
102 verbose:
103 Display stack contents while evaluating the expression if verbose is True
104
105 Returns
106 -------
107 float
108 The evaluated value
109 """
110 if not post_fix:
111 return 0
112 # Checking the list to find out whether the postfix expression is valid
113 valid_expression = [parse_token(token) for token in post_fix]
114 if verbose:
115 # print table header
116 print("Symbol".center(8), "Action".center(12), "Stack", sep=" | ")
117 print("-" * (30 + len(post_fix)))
118 stack = []
119 for x in valid_expression:
120 if x not in OPERATORS:
121 stack.append(x) # append x to stack

Callers 1

Calls 3

parse_tokenFunction · 0.85
appendMethod · 0.45
popMethod · 0.45

Tested by

no test coverage detected