Tuesday, August 29, 2017

[Solved] Python Quiz : 001

I came across a very simple Python Quiz question in a newsgroup, so thought about expanding on that.

Assuming, you are attending an interview and this question is asked. What would be your answer ?

[ Remember : you need to give this answer from memory and not by trying out this code :-) ]

>>> def foo(num) : print num; return num
...
>>>
>>> foo(5) * foo(1) * foo(2)
5
1
2
10
>>> foo(5) ** foo(1) ** foo(2)

And, as in any good interview, you are asked to explain your answer as well :-)

Post your answers in the comments below
    • There are two parts to this problem.
      1> Order of the execution of the functions
      2> Order of evaluation of the expression that involves **

      From the example mentioned in the earlier part of the question, its very evident that Python invokes these functions from left to right.

      So, that the expression to evaluate, after the functions return their values, would be
      >>> 5 ** 1 ** 2

      ** or exponentiation is the only operator in Python that is right-associative.

      The reason [ as far as I can understand ] for this behaviour, is that, it is the way it is handled in mathematics as well. It adds confusion only when the programming language, evaluates every other operator using left-association

      This link gives a very good explanation on why right-associativity is preferred : https://core.tcl.tk/tips/doc/trunk/tip/274.md

      Thus,
      >>> 5 ** 1 ** 2
      evaluates as
      >>> 5 ** (1 ** 2)
      >>> 5 ** ( 1 )
      >>> 5

      CONGRATULATIONS !!! to all those who got the result and the explanation right :-)

No comments:

Post a Comment