+ 3
BIT SHIFTING OPERATION.
hi class, suppose a = list(range(17)) then a =[0,1,2,3,4,...16] . Then result = [x: x&0 for x in a]. FYI, this is a kind of bit shifting operation which is performed in binary level compared each bit one by one. So, if we know that, then if sum is declared and initialized to 0, what is the result of: for i in result:result = [x: x & 1 for x in a] ? I guess it must be 1 itself. Sum += i Now, what is the result if we change : print(sum) I think the output will be 0. Can you help me to solve this?
7 ответов
+ 7
Oliver Pasaribu ,
> please link the original code you have done here.
> also provide a proper task description.
comment to your code:
if this:
...
result = [x: x&0 for x in a]
...
is meant as a comprehension, it will raise a syntax error.
should be:
result = [x&0 for x in a]
+ 3
Oliver Pasaribu
x & 1 produces a value that is either 1 or 0, depending on the least significant bit of x: if the last bit is 1, the result of x & 1 is 1; otherwise, it is 0. This is a bitwise AND operation.
Simply put, x & 1 is an even/odd mask. it will return 1 if x is odd and 0 if x is even.
so
print([x & 1 for x in range(10)])
will give you
[0, 1, 0, 1, 0, 1, 0, 1, 0, 1]
x & 0 is the same as x * 0 which will always return 0.
so
print([x & 0 for x in range(10)])
will give you
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
and yes, Lothar is right, your lambda expression inside a list comprehension is a syntax error. We often lambda expressions on lists as arguments for higher order functions like map or reduce.
so something like:
print([ i for i in map(lambda x: x & 1, range(10))])
which is just a more inefficient and verbose way of this:
print([x & 1 for x in range(10)])
also look up
x>>1
https://stackoverflow.com/questions/38922606/what-is-x-1-and-x-1
+ 1
Write the code and test it. Try variations and see the results.
+ 1
Wait wait.
A = list(range(10))
A = [0,1,2,3,4,5,6,7,8,9]
B = [X & 0 for X in A]
B = [0&0, 1&0, 2&0, 3&0, 4&0, ... 9&0]
In binary:
B[0] = 00000000
00000000 &
--------------------
00000000 = 0 = False = 0 decimal
B[1] = 1&0 in binary:
00000001
00000000 &
----------------------
00000000
B[2] = 00000010
00000000 &
--------------------
00000000
until B[9]
B[9] = 00001001
00000000 &
--------------------
00000000 = 0 DECIMAL
henceforth we obtain:
B = [X& 0 for X in A]
= [0,0,0,0,0,0,0,0,0]
Is it correct?
+ 1
If A = [0,1,2,3,4,5,6,7,8,9]
and B = [X & 1 for X in A], then:
B [0] = 00000000
00000001
------------------&
00000000 = 0 decimal.
B[1] = 00000001
00000001
------------------ &
00000001 = 1 DECIMAL
B[2] = 00000010
00000001
-----------------&
00000000
B[3] = 00000011
00000001
------------------&
00000001 = 1 DECIMAL
alternatively B[n] = 0 in n == even, or 1 if n= odd.
B = [0, 1, 0, 1, 0, 1, 0, 1, 0, 1].
0
yes
0
Ch mariyadasu