150. evaluate reverse polish notation
class Solution(object):
def evalRPN(self, tokens):
"""
:type tokens: List[str]
:rtype: int
"""
queue = []
for item in tokens:
if item == "*" or item == "/" or item == "+" or item == "-":
operand2 = queue.pop()
operand1 = queue.pop()
result = self.calc(item, operand1, operand2)
queue.append(result)
else:
queue.append(int(item))
<span class="k">return</span> <span class="n">queue</span><span class="o">.</span><span class="n">pop</span><span class="p">()</span>
<span class="k">def</span> <span class="nf">calc</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">op</span><span class="p">,</span> <span class="n">op1</span><span class="p">,</span> <span class="n">op2</span><span class="p">):</span>
<span class="k">if</span> <span class="n">op</span> <span class="o">==</span> <span class="s">"*"</span><span class="p">:</span>
<span class="k">return</span> <span class="n">op1</span> <span class="o">*</span> <span class="n">op2</span>
<span class="k">elif</span> <span class="n">op</span> <span class="o">==</span> <span class="s">"/"</span><span class="p">:</span>
<span class="k">if</span> <span class="n">op1</span> <span class="o">*</span> <span class="n">op2</span> <span class="o"><</span> <span class="mi">0</span><span class="p">:</span> <span class="c"># python是向下取整,即5/(-3)=-2</span>
<span class="k">return</span> <span class="o">-</span><span class="p">((</span><span class="o">-</span><span class="n">op1</span><span class="p">)</span> <span class="o">/</span> <span class="n">op2</span><span class="p">)</span>
<span class="k">else</span><span class="p">:</span>
<span class="k">return</span> <span class="n">op1</span> <span class="o">/</span> <span class="n">op2</span>
<span class="k">elif</span> <span class="n">op</span> <span class="o">==</span> <span class="s">"+"</span><span class="p">:</span>
<span class="k">return</span> <span class="n">op1</span> <span class="o">+</span> <span class="n">op2</span>
<span class="k">else</span><span class="p">:</span>
<span class="k">return</span> <span class="n">op1</span> <span class="o">-</span> <span class="n">op2</span>
if name == 'main':
answer = Solution()
print answer.evalRPN(["10","6","9","3","+","-11","","/","","17","+","5","+"])