python - Shorthand code and Fibonnaci Sequence -
this question has answer here:
i have found example fibonacci sequence goes this:
def fib(n): a, b = 0, 1 while b < n: print (b) a, b = b, a+b fib(20) so here's don't it:
a, b = 0, 1 # shortcut writing = 0 b = 1 right?
now, following same logic
a, b = b, a+b #should same writing = b b = a+b but isn't because if write that, output different. i'm having hard time understanding why. thoughts?
yes isn't same , because when write -
a, b = b, a+b the value of a , b @ time of executing statement considered, lets before statement, a=1 , b=2 , first right hand side calculated , b=2 calculated , a+b=3 calculated. assignment occurs, a assigned value 2 , b assigned value 3.
but when write -
a = b b = a+b the assignment occurs along calculation, first b=2 calculated, assigned , becomes 2 , a+b calculated (with changed value of a) , a+b=4 , assigned b , b becomes 4 , , hence difference.
a,b = b, this shorthand swapping values of a , b , please note if want swap values without using notation, need temporary variable.
internally how works right hand sid made tuple, , values unpacked, simple test see -
>>> = 5 >>> b = 10 >>> t = a, b >>> t (5, 10) >>> b, = t
Comments
Post a Comment