Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>General suggestions:</p> <ul> <li>Avoid unnecessary type checks, and rely on default exception behavior.</li> <li><a href="http://docs.python.org/library/stdtypes.html#dict.has_key" rel="noreferrer"><code>has_key()</code></a> has long been deprecated in favor of the <code>in</code> operator: use that instead.</li> <li><a href="http://docs.python.org/library/profile.html" rel="noreferrer">Profile</a> your program, before attempting any performance optimization. For a zero-effort profiling run of any given code, just run: <code>python -m cProfile -s cumulative foo.py</code></li> </ul> <p>Specific points:</p> <ul> <li><code>list</code> <a href="http://docs.python.org/tutorial/datastructures.html#using-lists-as-stacks" rel="noreferrer">makes a good stack</a> out of the box. In particular, it allows you to use <em>slice notation</em> (<a href="http://docs.python.org/tutorial/introduction.html#lists" rel="noreferrer">tutorial</a>) to replace the <code>pop</code>/<code>pop</code>/<code>append</code> dance with a single step.</li> <li><code>ARITHMETIC_OPERATORS</code> can refer to operator implementations directly, without the <code>getattr</code> indirection.</li> </ul> <p>Putting all this together:</p> <pre><code>ARITHMETIC_OPERATORS = { '+': operator.add, '-': operator.sub, '*': operator.mul, '/': operator.div, '%': operator.mod, '**': operator.pow, '//': operator.floordiv, } def postfix(expression, operators=ARITHMETIC_OPERATORS): stack = [] for val in expression.split(): if val in operators: f = operators[val] stack[-2:] = [f(*stack[-2:])] else: stack.append(int(val)) return stack.pop() </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload