+ 4
Can someone please explain this piece of code please
this was a part of quiz and I tried reviewing the relevant lesson but I couldn't understand . def cm (): return [lambda x: x*i for i in range (3) for m in cm (): print (m (1)) is m another function ? and why does it give the same result 3 times?
6 Antworten
+ 8
It is not intuitive to comprehend at first glance.
You define the cm() method to return a list. This list contains a lambda function which is executed 3 times. What each of the iterations return is the last value of the range, thus 2. So on its own, the cm() method returns an iterator of functions.
Now, you iterate over this, assuming the value passed to the "iterator of functions" as 1. So it prints 1*2 exactly 3 times.
If you pass 10 and change the range argument to 4, you will get four times the 3* 10, so:
30
30
30
30
+ 3
ok. the fact that cm() could be an iterator of functions was a bit hard to grasp, but I think i understand it a little bit more now. thank you ☺
+ 2
Change lambda section in your code like below. You will get your desired output.
[lambda x: [x*i for i in range(3)]]
With that we create a list comprehensive inside lambda expression.
+ 2
I know that anyway thanks for your explanation. My solution is specific for the problem. It may not work for other situations.
+ 1
I don' t undestand , isn't "i" going to take all the values from 0 to 2 , thus cm() should contain 3 fonctions with the first returning x*0 ,the second x*1 and the third x*2 ???
+ 1
Servet it's a good idea but I think u have gone around the problem, we want to create a function that returns a list of functions , but what you have done here is u created a function that returns a list with one element (a lambda funcion ) wich returns a list of integers/floats or whatever , however your solution will give the intended result in this case but in an other situation where I want to manipulate each function in the list that cm() returns separately this won't work, actually u will get some errors too.