I wrote this line:
a = [lambda x : x^n for n in range(10)] In addition, at each iteration
for i in range(10): print(a[i](2)) gives out 11, a
for i in range(10): print(a[2](i)) Output: 9 8 11 10 13 12 15 14 1 0
Why?
If I understand correctly, the following happens:
a = [lambda x : x^n for n in range(10)] - a list of functions is created here. This is the same as:
def xoring(x): for n in range(10): pass return x^n a = [] for i in range(10): a.append(xoring) You can even see what's inside the list and see a set of functions:
>>> a [<function <listcomp>.<lambda> at 0x029E1468>, <function <listcomp>.<lambda> at 0x02B7C300>, <function <listcomp>.<lambda> at 0x02B7C348>, <function <listcomp>.<lambda> at 0x02B7C390>, <function <listcomp>.<lambda> at 0x02B7C3D8>, <function <listcomp>.<lambda> at 0x02B7C420>, <function <listcomp>.<lambda> at 0x02B7C468>, <function <listcomp>.<lambda> at 0x02B7C4B0>, <function <listcomp>.<lambda> at 0x02B7C4F8>, <function <listcomp>.<lambda> at 0x02B7C540>] Further, for i in range(10): print(a[i](2)) , the i-я function from the list a is called 10 times and the argument 2 is passed to it. Since the functions are the same, the results are the same. Those. the following happens inside:
lambda x : x^n for n in range(10) - here i changes from 0 to 9 and rises from x . Because x = 2, then x^i will give the following results:
2^ 0 = 2 2^ 1 = 3 2^ 2 = 0 2^ 3 = 1 2^ 4 = 6 2^ 5 = 7 2^ 6 = 4 2^ 7 = 5 2^ 8 = 10 2^ 9 = 11 The last value and function returns.
Here, for i in range(10): print(a[2](i)) function with index 2 in the list a is called 10 times and the value i is passed to it, which varies from 0 to 9 . Same thing as
for i in range(10): print(xoring(i)) As a result, and gives
0 ^ 9 = 9 1 ^ 9 = 8 2 ^ 9 = 11 3 ^ 9 = 10 4 ^ 9 = 13 5 ^ 9 = 12 6 ^ 9 = 15 7 ^ 9 = 14 8 ^ 9 = 1 9 ^ 9 = 0 Do you really need to XOR- x^n ( x^n ) numbers in the decimal system? I will assume that you wanted to perform an exponentiation operation ( x**n ). When generating your list of anonymous functions, they all depend on the variable n , whose value at the end of the loop is n = 9 .
In addition, at each iteration
for i in range(10): print(a[i](2)) gives out 11
This is understandable, because all the functions in the list return the value x^9 .
If you still need exponentiation:
fun = lambda n: lambda x: x**n a = [fun(n) for n in range(10)] for i in range(10): print(a[i](2), end=' ') Out: 1 2 4 8 16 32 64 128 256 512 Source: https://ru.stackoverflow.com/questions/533585/
All Articles