+ 1

Python sololearn challenge doubt

The output of this code: def cm(): return[lambda x: i*x for i in range (3)] for m in cm(): print(m(1)) Is: 222 Why is that? I don't understand what is it doing?

19th Jun 2017, 1:23 PM
Vigegar
6 odpowiedzi
+ 6
I remember tackling this one already somewhere here. The cm() method, instead of fixed values, returns a list of lambda functions. Those, in turn, when iterated with an argument, assume their last multiplication value on exit, when the print is executed. This is why the range(3), m(1) prints out 1*2 three times, while range(10) and m(2) prints out 2*9 - ten times.
19th Jun 2017, 4:00 PM
Kuba Siekierzyński
Kuba Siekierzyński - avatar
+ 6
@Baard Exactly. type(m) returns 'function' as m is a lambda (class 'function'). But type(m(1)) would return an integer (class 'int'), as this function returns integer as a result.
19th Jun 2017, 7:13 PM
Kuba Siekierzyński
Kuba Siekierzyński - avatar
0
Surprising code ... for loop counts up i, x*i sets x to the value of i, x is returned to caller of cm, why the print () only print the same I can't understand. print (m (1)) multiply m with 1and print it ...... wierd code. 😱 I can't explain it, play with the range of cm () for loop and replace the (m(1)) with a different numer. With range (10) and (m(2)) the output is 10 lines of 18 add print(m) ... and it gets weirder grrrr
19th Jun 2017, 3:26 PM
Baard Helmen
Baard Helmen - avatar
0
yes, bc the value of m is: <function.cm. <locals>. <listcomp>. <lambda> at 0x7fde9ddxxxxx>. The last will be an address .... That didn't give me much to go on further. Great job Kuba
19th Jun 2017, 4:07 PM
Baard Helmen
Baard Helmen - avatar
0
I just checked with print(type(m)) and it return the type of variable is a class 'function'
19th Jun 2017, 4:11 PM
Baard Helmen
Baard Helmen - avatar
0
Someone was trying WAAAY too hard with that challenge. Because returning a list of lambdas creates a very strange behavior in Python - basically, all the lambda functions returned behave just like the last one. So no matter which of them you call, they will all return 2*x in this case (with 2 being the last value for i). If you're curious as to why, see here: https://stackoverflow.com/questions/233673/lexical-closures-in-python So this also answers the problem noticed by @Baard and @Kuba :) It would be really nice if people submitting challenges would focus more on programming and less on weird/corner case behaviours....
20th Jun 2017, 7:52 AM
Bogdan Sass
Bogdan Sass - avatar