+ 2
For I in range (17):?
What is the output of this code? I=[ ] for i in range(17): l.append(i * 3) m = [x&1 for x in I] print(sum(m)) Output: 8 Append means place something in the back of the list. Range is 0-17. So not sure if I should take everything times three? Also, what does [x&1 for x in l] mean? Thanks for any help anyone could provide:).
3 Respostas
+ 4
The indentations for the code are off, so I'm assuming
l = []
for i in range(17):
l.append(i*3)
m = [x&1 for x in l]
print(sum(m))
range(17) returns 0 to 16, so list l with contain 0*3, 1*3, 2*3... , 16*3
[x&1 for x in l] builds a new list consisting of every element in list l, after you bitwise AND them with 1.
https://www.tutorialspoint.com/JUMP_LINK__&&__python__&&__JUMP_LINK/bitwise_operators_example.htm
You can always try to print the list contents if you're not sure what the code does.
l = []
for i in range(17):
l.append(i*3)
print(l)
m = [x&1 for x in l]
print(m)
print(sum(m))
+ 4
m = [
0&1
00000000
&
00000001
=
00000000,
3&1
00000011
&
00000001
=
00000001,
6&1
00000110
&
00000001
=
00000000,
9&1
00001001
&
00000001
=
00000001,
12&1
00001100
&
00000001
=
00000000,
15&1
...] => m=[0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0]
As a result, when x is equal to odd numbers, x&1 = 1, x&2 = 2, x&3 = 3, ...
+ 1
Thanks Fermi and Vasiliy:).