I want the step by step explanation of the following code:
print(1 | 0 ^ 1 & ~0)
I tried with the output bit (output with first and second bit) and got the answer as 0. The tilde function got me hooked up for some time I found it a bit hard. The answer is 1.
First you must understand what each operator does
| - Bitwise OR: Returns True (1) if either of its operands is 1. e.g.
1 | 0 == True
& - Bitwise AND: Returns True if both of its operands are 1. e.g.
0 & 1 == False
^ - Bitwise XOR: Returns True if only one of its operands is 1. e.g.
0 ^ 1 == True
~ - Bitwise NOT: Flips the bit of its operand.
edit: As noted by Daniel Martin, In Python specifically, it flips all of the bits of an arbitrary integer. The formula would be ~x == -x - 1 e.g.
~0 == -1
Then you must understand the order of bitwise operations
In order of precedence:
~ -> & -> ^ -> |
Solving the expression in that order
1 | 0 ^ 1 & ~0 == 1 | 0 ^ 1 & -1 - ~ is applied first
1 | 0 ^ 1 & -1 == 1 | 0 ^ 1 - & is applied second
1 | 0 ^ 1 == 1 | 1 - ^ is applied third
1 | 1 == 1 - | is applied last
Okay, first let's put some parentheses in that code to show how the order of operations applies in python:
print(1 | 0 ^ 1 & ~0)
becomes
print(1 | (0 ^ (1 & (~0))))
Okay, all good.
Now then, first we'll go through what ~0 means, then we'll consider what 1 & (~0) is, then 0 ^ (1 & (~0)), then 1 | (0 ^ (1 & (~0))).
Because these are all bitwise operations, I'm going to flip back and forth between decimal and binary without warning. I hope you've had a basic introduction to what binary is.
So, first ~0. In languages with integer types that have a specific width, (e.g. in C or C++) ~0 would mean "a value that in binary is all 1 bits, as wide as the type", since ~ means "flip all the bits" and 0 is represented with all bits 0. But since python's integers don't have a specific width that would mean "a value that in binary is an infinite sequence of 1 bits", and so we have to fall back on what it says in the documentation:
The unary ~ (invert) operator yields the bitwise inversion of its integer argument. The bitwise inversion of x is defined as -(x+1). It only applies to integral numbers or to custom objects that override the __invert__() special method.
So ~0 is -1.
Now, what's 1 & (-1) ? Well, in binary 1 is just 1, and -1 is all 1 bits, as large as you might want. So the bitwise & of those two values is just 1, since for bitwise & the output has a 1 bit only where both inputs have a 1 bit.
Now, 0 ^ (1). Well, we know what 0 looks like in binary, and we know what 1 looks like in binary (they look just like decimal), and with ^ the output has a 1 bit only where the output and input differ. So 0 ^ 1 is just 1.
Now 1 | (1). This is just 1, by the definition of |.
In a way, python makes reasoning this out harder than it would be in C or many other languages by not having a fixed size for its integers, so when dealing with ~0 you have to briefly imagine that there's this infinite string of 1s that you're dealing with, but it isn't that bad.
Related
I have two expressions like given below:
a,b,c=2,4,5
print(a|b*c)
output : 22
How it is returning me the 22
and second expression is :
print(a|b^c)
output : 3
Can anyone please explain to me how python calculating this? I am a newbie in python I don't know how it is calculating this.
print(a|b*c)
Because of the operator precedence, the multiplication (*) will be processed before the bitwise OR (|), so the operations will happen in the following order:
b*c = 4*5 = 20
a|b*c = 2|20, i.e 10 OR 10100 = 10110 in binary
That gives us a final answer of 22.
print(a|b^c)
Likewise, due to the operator precedence, the bitwise XOR (ˆ) will be processed first, so we'll have:
bˆc = 4ˆ5, i.e 100 XOR 101 = 001 in binary
a|bˆc = 2|1, i.e 10 OR 01 = 11 in binary
That gives us a final answer of 3.
EXPRESSION # 1
Lets consider,
a|b*c
Precedence of * (multiplication) is greater than | (bitwise OR) thats why first b*c will be computed and then its output will be computed with a
STEPS:
1- b*c will return 20.
2- Then a will perform bit wise OR operation with b*c. See Bitwise OR operation ( OR returns 1 when there is any one else 0)
3- Convert values of a and b*c to binary and perform bitwise operation. See Convert decimal to binary
1 0 > a = 2
1 0 1 0 0 > b*c = 20
_________
1 0 1 1 0 > a|b*c = 22
EXPRESSION # 2
Lets consider,
a|b^c
Precedence of ^ (bitwise XOR) is greater than | (bitwise OR) thats why first b^c will be computed and then its output will be computed with a
STEPS:
1- Bitwise XOR operation will be performed between b and c (b^c). See Bitwise XOR operation ( XOR returns 1 when there are odd number of ones else 0)
1 0 0 > b = 4
1 0 1 > c = 5
______
0 0 1 > b^c = 1
2- Then a will perform bit wise OR operation with b^c. See Bitwise OR operation ( OR returns 1 when there is any one else 0)
1 0 > a =2
0 1 > b^c = 1
___
1 1 > a|b^c = 3
You need to break down the numbers into their binary representation to see what's happening under the hood.
Case 1,
Binary for a (2) - 00010
Binary for b*c (20) - 10100
So if you do a bitwise OR (|) you'll get a binary sum of above two i.e. 10110 = 22
Case 2,
Binary for a (2) - 00010
Binary for b (4) - 00100
Binary for c (5) - 00101
Again if you do a bitwise XOR (^) you'll get a binary exclusive or of b and c i.e. 00001= 1
Finally if you do a bitwise OR (|) you'll get a binary sum of a with b^c i.e. 00011 = 3
This is doing a mix of bitwise and integer arithmetic operations.
How does that work?
Based on the order of precedence of operators defined in the docs, the first expression to be evaluated is b*c, which returns 20. Then we evaluate the expression a|20. This is a bitwise operation on the two integers, so what we are doing is doing a logical OR on each bit of the binary representation of these two numbers i.e. (00010) | (10100) which gives us (10110) i.e. 22
Similarly, in the second example, we first do XOR on b and c, which is equal to 1 (calculated as binary 100 XOR 101 = 001). The result is then bitwise ORed with a, returning the value 3
The Precedence of arithmetic operators *, / , +, - is more than
bitwise operators &, |, ^ and both types of operators are evaluated left to right if the same precedence is found.
Moreover,
for arithmetic operator precedence order is : *,/ then +,-
and for bitwise operator precedence order is: & , ^, |
Check this article for more information
Coming to the solution:
The first expression evaluates like this: a|(b*c)
The second expression evaluates like this: a|(b^c)
Coming from a Java background into Python and working my way through CodingBat (Python > Warmup-1 > pos_neg) the following confused me greatly:
>>> True ^ False
True
>>> 1<0 ^ -1<0
False
I appreciate the following:
>>> (1<0) ^ (-1<0)
True
But what is python interpreting 1<0 ^ -1<0 as to return false?
^ has higher precedence than <.
Thus, what is being evaluated is actually 1 < -1 < 0, where 0 ^ -1 = -1
And thus you rightly get False, since the inequality clearly does not hold.
You almost never have to remember the precedence table. Just neatly use parenthesis.
You might want to check this out as well, which discusses an identical situation.
0 ^ -1 equals -1. 1 < -1 < 0 is False since 1 is greater than -1. Python chains relational operators naturally, hence 1 < -1 < 0 is equivalent to (1 < -1) and (-1 < 0).
This question already has answers here:
What does the caret (^) operator do?
(5 answers)
Closed 9 years ago.
I'm struggling to find documentation on what the ^ does in python.
EX.
6^1 =
7
6^2 =
4
6^3 =
5
6^4 =
2
6^5 =
3
6^6 =
0
Help?
It is the bitwise exclusive-or operator, often called "xor". For each pair of corresponding bits in the operands, the corresponding bit in the result is 0 if the operand bits are the same, 1 if they are different.
Consider 6^4:
6 = 0b0110
4 = 0b0100
6^4 = 0b0010 = 2
As you can see the least-significant bit (the one on the right, in the "one's" place) is zero in both numbers. Thus the least-significant bit in the answer is zero. The next bit is 1 in the first operand and 0 in the second, so the result is 1.
XOR has some interesting properties:
a^b == b^a # xor is commutative
a^(b^c) == (a^b)^c # xor is associative
(a^b)^b == a # xor is reversible
0^a == a # 0 is the identity value
a^a == 0 # xor yourself and you go away.
You can change the oddness of a value with xor:
prev_even = odd ^ 1 (2 = 3 ^ 1)
next_odd = even ^ 1 (3 = 2 ^ 1)
for more information on XOR , please react the documentation on Python.org at here:
http://docs.python.org/2/library/operator.html
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about a specific programming problem, a software algorithm, or software tools primarily used by programmers. If you believe the question would be on-topic on another Stack Exchange site, you can leave a comment to explain where the question may be able to be answered.
Closed 9 years ago.
Improve this question
I'm confused with the logic of 1% 2 will be 1. Because from what I know 1/2 is 0 so there is no remainder for this.
1/2 is 0 with a remainder of 1. The % operator returns that remainder.
% returns the remainder of a / b:
>>> 1 % 2
1
>>> 1/2
0
>>> 1 - 0
1
Also, the modulo expression can be expressed as:
r = a - nq
Where q is floor(a/n). So:
>>> import math
>>> 1 - 2 * math.floor(1/2)
1.0
% is the modulo operator. It returns the remainder after dividing the left hand side by the right hand side. Since 2 divides zero times into 1, the remainder is one.
In general, if a and b are positive integers, and a < b, then a % b == a.
The arguments do not need to be integers, though. More detail is available from the python reference documentation (http://docs.python.org/2/reference/expressions.html):
The % (modulo) operator yields the remainder from the division of the first argument by the second. The numeric arguments are first converted to a common type. A zero right argument raises the ZeroDivisionError exception. The arguments may be floating point numbers, e.g., 3.14%0.7 equals 0.34 (since 3.14 equals 4*0.7 + 0.34.) The modulo operator always yields a result with the same sign as its second operand (or zero); the absolute value of the result is strictly smaller than the absolute value of the second operand [2].
The integer division and modulo operators are connected by the following identity: x == (x/y)*y + (x%y). Integer division and modulo are also connected with the built-in function divmod(): divmod(x, y) == (x/y, x%y). These identities don’t hold for floating point numbers; there similar identities hold approximately where x/y is replaced by floor(x/y) or floor(x/y) - 1 [3].
Certainly there is a remainder. How many 2s can you get out of 1? 0 of them, with 1 left over.
Ok, the answer has been posted like 6 times already, just adding this for completeness, If there's one way to understand modulo (%), it's converting from base 10 to base 2, 1 can't be divided by 2 so we leave it alone (get a remainder of 1). You can imagine the binary numbers in the third column to be the results of a modulo operation.
eg. 9 (base 10) to (base 2)..
2 | 9 | 1
2 | 4 | 0
2 | 2 | 0
2 | 1 | 1
2*0 is 0
hence the remainder is 1
if the question is to find m%n
we find smallest or equal q such that n*(some whole number) = q and q<=m
we then find (m-q) which is the remainder..
What the % operator is doing:
a % b equals a value c such as 0 <= c < b and there exists a number k so that b * k + c = a.
How does Python evaluate the expression 1+++2?
How many ever + I put in between, it is printing 3 as the answer. Please can anyone explain this behavior
And for 1--2 it is printing 3 and for 1---2 it is printing -1
Your expression is the same as:
1+(+(+2))
Any numeric expression can be preceded by - to make it negative, or + to do nothing (the option is present for symmetry). With negative signs:
1-(-(2)) = 1-(-2)
= 1+2
= 3
and
1-(-(-2)) = 1-(2)
= -1
I see you clarified your question to say that you come from a C background. In Python, there are no increment operators like ++ and -- in C, which was probably the source of your confusion. To increment or decrement a variable i or j in Python use this style:
i += 1
j -= 1
The extra +'s are not incrementors (like ++a or a++ in c++). They are just showing that the number is positive.
There is no such ++ operator. There is a unary + operator and a unary - operator though. The unary + operator has no effect on its argument. The unary - operator negates its operator or mulitplies it by -1.
+1
-> 1
++1
-> 1
This is the same as +(+(1))
1+++2
-> 3
Because it's the same as 1 + (+(+(2))
Likewise you can do --1 to mean - (-1) which is +1.
--1
-> 1
For completeness there is no * unary opeartor. So *1 is an error. But there is a **
operator which is power of, it takes 2 arguments.
2**3
-> 8
1+(+(+2)) = 3
1 - (-2) = 3
1 - (-(-2)) = -1
Trying Unary Plus and Unary minus:
The unary - (minus) operator yields the negation of its numeric argument.
The unary + (plus) operator yields its numeric argument unchanged.
>>> +2
2
>>> ++2
2
>>> +++2
2
>>> -2
-2
>>> --2
2
>>> ---2
-2
>>> 1+(++2)
3
I believe it's being parsed as, the first + as a binary operation (add), and the rest as unary operations (make positive).
1 + (+(+2))
Think it as 1 + (+1*(+1*2))). The first + is operator and following plus signs are sign of second operand (= 2).
Just like 1---2 is same as 1 - -(-(2)) or 1- (-1*(-1*(2))