Q: Operator precedence

Joshua Marshall jmarshal at mathworks.com
Mon Mar 5 12:20:01 EST 2001


Raymond Hettinger <othello at javanet.com> wrote:
> Pearu Peterson wrote:

>> Section 5.12 in Python reference manual summarizes operator precedence.
>>
>> I would like to have the following function:
>>
>> def getprec(s):
>>      return <the precedence number of a keyword/operator `s'>

> Here is an approach to rank ordering of precedence at run-itme:

> def higherOrEqual( op1, op2 ):
>     return eval('51 %s 83 %s 97 == ( 51 %s 83 ) %s 97' % (op1,op2,op1,op2))

> order = ['Lower', 'HigherOrEqual']

> binops = ['+', '-', '&', '^', '/']

> for x in binops:
>     for y in binops:
>         print x, order[higherOrEqual(x,y)], y

This will fail for '**', since it's right-associative.
(Ignoring integer overflow and computation time.)



More information about the Python-list mailing list