+ 1
Explain this code
def f1(x): for num in x: if num%2==0: yield num def f2(x): for num in x: yield num*3 def f3(x): for num in x: yield num x=[0,-1,-4,-9,-16,-25,-36,-49] result=f3(f2(f1(x))) for num in result: print(num,end='')
3 Answers
+ 4
f1, f2, and f3 are all generators (kind of dynamic list)...
the first iterate the list passed as argument (and is called first as is inner of both other argument) and filter them by returning only the even number in it (num%2==0 is true for even numbers and so yield return them one at a time).
the second multiply each of the filtered numbers by 3, and the third do nothing else than returning each (f3 in this case is useless and could be avoided).
so finaly result contains all even numbers from x multplied by 3, and you print each one by one, but on one line without separation (default end parameter new line is forced to be avoided by passing an empty string, while default separator is no used as you only give one argument at a time to the print function)
+ 6
here is also a short introduction from sololearn about generators:
https://www.sololearn.com/learn/JUMP_LINK__&&__Python__&&__JUMP_LINK/2462/?ref=app
+ 2
Explanation
1)with yield key word , all functions become generators,
in this code f1 , f2 , f3 are generators and generators are special types of iterators .
2)with for loop , in functions f1 , f2 , f3 you are operating on each element of list x, every time you will operate on same list, which is x.
I hope , this explanation will help you in understanding above code.
Happy learning :)