Python Exponentiating Operator - python

Could someone help me to understand the following statement?
Why this is True:
3.0 == 3
but this one not?
4 ** 0.5 != 2
(4**0.5 = 2.0, and according to above statement 2.0 is equal to 2), but I get False. WHy?

The != operator does the opposite of ==.
(In your first example, you wrote = but I think you mean ==.)
With !=, it evaluates True if the two numbers are not equal to each other, otherwise it is False. (Here, "equal" can include an integer and a floating point number having the same numerical value.)
So here:
>>> 4 ** 0.5 != 2
False
>>> 4 ** 0.5 == 2
True

Unlike some languages, Python does not care about floats and ints when it comes to comparing. It will treat 4 and 4.0 as the exact same when comparing them to other numbers. You can debate the reliability of this feature of Python, but for the purposes of answering this question this is relevant.
Now we know this, we can see that 4 * .5 is the same is 2.0 which is the same as 2. The actual reason the second argument is false has nothing to do with the number being a float or not, but actually to do with the operator you are using.
== will return true if both sides of the equation ARE equal, whereas != will return true if both sides of the equation ARE NOT equal.
The second statement is using the != operator and so is returning false because both sides are equal. If both sides where not equal, it would return false.
Hope this cleared things up!

Related

Is this recursion is posible?

Can someone please explain to me how this piece of recursive code is working? Because there is only one if statement which checks if variable x is equal to zero and returns true if the value is equal to zero.
And the other part is just upon calling each other.
def is_even(x):
if x == 0:
return True
else:
return is_odd(x-1)
def is_odd(x):
return not is_even(x)
print(is_odd(17)) # outputs true
print(is_even(23)) # outputs false
This pair of mutually recursive functions makes use of three facts:
0 is even
x is even if x - 1 is odd.
x is odd if x - 1 is even.
1 is odd because 1 - 1 == 0 is even.
2 is even because 2 - 1 == 1 is odd.
And so on.
This is not an efficient way to determine if an arbitrary value n is even or odd, but it is a logically correct way. (Assuming the argument is always a natural number, anyway. Passing a negative integer as an argument to either results in infinite recursion, as the base case will never be reached.)
I want to give a simpler answer to follow along with. Think about the stack trace. I'll abbreviate is_even and is_odd as IE and IO respectively.
IO(17)
NOT[IE(17)]
NOT[IO(16)]
NOT[NOT[IE(16)] = IE[16]
IO(15)
...
This is basically checking if alternating descending numbers starting from the input value are even and odd all the way down to 0. Note that if we start with a true statement (like IO(17)) then every line contains a true statement - if we started with a false statement, every line ends up with a false statement. Following the pattern we see here, we see that the final state can therefore end up as
IE(1) -> IO(0) -> NOT[IE(0)] = NOT[True] = False # as expected!
OR
IO(1) -> NOT[IE[1]] = NOT[IO[0]] = NOT[NOT[IE(0)] = NOT[NOT[True]] = True # likewise!

Using IF, AND, OR together with EQUAL operand together in Python [duplicate]

This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 6 years ago.
I'm trying to create a function where the given value (passed as a string) is checked to see if the number of digits is either 4 or 6, and that it is a number.
My first impulse was to go with this code:
def number(x):
if (len(x) == (4 or 6)) and x.isdigit():
print "True"
else:
print "False"
This code above only passes the first test below...I don't understand why it passes this but none of the other tests:
number("1234")
Only when I separate out the len() functions will it work properly.
def number(x):
if (len(x) == 4 or len(x) == 6) and x.isdigit():
print "True"
else:
print "False"
## Checks
number("1234")
number("123456")
number("abcd")
number("abcdef")
number("1")
number("a")
The above code passes all tests.
So my questions are:
What's going on here?
Any way to write cleaner code for this?
Thank for the help!
** Not a duplicate question because although this question has the same underlying concepts regarding boolean operators, the problem itself is different due to the usage of len(), isdigit(), and the additional question of how best to improve it (someone commented the usage of return). Definitely adds another perspective to the other question though.
It helps to examine the logic of this line:
if (len(x) == (4 or 6)):
The (4 or 6) clause contains a logical or short circuit. The value 4 is true, so it is evaluated and returned to the == relational comparison.
The way that or works is that its lefthand side is evaluated for Boolean truth, and its value is returned if true. If the lefthand side is not Boolean true, then the righthand side is evaluated and its value is returned.
Because the lefthand side of the 4 or ... is true in a Boolean sense, the righthand side is never evaluated. Python doesn't even look past 4 or. If the left-hand value were a false value (such as 0), then the right hand side of the or would be evaluated.
To see this in action, try print 4 or 6. The output will be 4.
So since the 4 is a hard-coded true value, your comparison is semantically the same as if (len(x) == 4) -- that is, since 4 is true, 6 is never evaluated.
What I suppose you really want to know is if len(x) is either 4 or 6. You could put that to code in a couple of ways:
if(len(x) == 4 or len(x) == 6 ...
if(len(x) in (4,6) ...
You can use the in operator like so:
def number(x):
if len(x) in (4, 6) and x.isdigit():
print "True"
else:
print "False"
where in checks for containment in a given container. Note that 4 or 6 on their own evaluate to something undesirable, which is why your first code segment fails. You can check it out on the python shell:
>>> 4 or 6
4
You probably wanted to write
if (len(x) in (4, 6)) and x.isdigit():
Instead of
if (len(x) == (4 or 6)) and x.isdigit():
Short answer: len(x) in [4, 6] or len(x) == 4 or len(x) == 6.
"or" is a boolean, or logical choice. (4 or 6) is guaranteed to resolve to a non-zero (true) value. In this case, it resolves to 4, so your test case passes.
I'll go ahead and answer
Any way to write cleaner code for this?
Yes. Return the boolean value, rather than printing a string.
def number(x):
return len(x) in {4, 6} and x.isdigit()
print(number("1234")) # True
Then, it is simple do use your method in a if-statement without string comparison.
The trouble is in your or statement.
Any value greater than one will evaluate to True when you put it in a conditional. So (4 or 6) will always resolve to true.
You could use the in statement above or you could just use two =='s:
if (len(x) == 4 or len(x) == 6) and x.isdigit()
It's a bit wordier, I find it easier to read.

Boolean logic in Python [duplicate]

This question already has answers here:
Is False == 0 and True == 1 an implementation detail or is it guaranteed by the language?
(3 answers)
Closed 8 years ago.
Can someone help to explain the following:
1 and 5
5 and 1
The above gives 5 and 1 respectively. Q1: Why is the and operator not commutative?
Next:
1==True # gives True
However:
5==True
5==False
both give False. Q2: Why?
https://docs.python.org/2/library/stdtypes.html section 5.1 says "... All other values are considered True", so 5 should be True.
From the documentation:
The expression x and y first evaluates x; if x is false, its value is returned; otherwise, y is evaluated and the resulting value is returned.
The expression x or y first evaluates x; if x is true, its value is returned; otherwise, y is evaluated and the resulting value is returned.
Note that here, if x is false means if bool(x) == False.
The answer to your first question about and is that the result of the and is the value of the first expression if it is False-like (0, False, None, etc.), otherwise it is the value of the second expression. A bunch of programming languages share this sort of construct; in some languages like Bash and Perl it's idiomatic to rely on it extensively. In Python we mostly use and for regular boolean logic and rely on it less often for short-circuiting.
As for 1==True being true but 5==True being false, well, frankly I wish 1==True also returned false but obviously it's too late to change it now. :)
In answer to your second part:
It's true that all non-zero integers are "Truthy" but this does not mean that 5 == True will return True. The == operator is comparing value and, when comparing values, 5 is not equal to True. If you compare bool(5) == True then that will return True. When you do if 5: what you actually are doing is if bool(5):.
The reason that 1 == True returns True is that in Python the boolean class is a subclass of int, with True being represented by 1 and False being represented by 0. So 1 == True returns True because they are equal.
Note that, as discussed in this question, this is NOT GUARANTEED in Python 2.x as True and False can be re-defined. In Python 3.x they are keywords which will always be equal to 1 and 0, respectively.

Python why 100**0.5 == 4+6 is true?

>>> 100**0.5 != 4+6
False
>>> 100**0.5 == 4+6
True
>>> 4+6
10
>>> 100**0.5
10.0
>>> 10.0==10
True
Who can tell me why 10.0==10 is True?
I think 10.0 is a float and 10 is int,I know in java they are not equal.
Quoting from http://docs.python.org/2/library/stdtypes.html#numeric-types-int-float-long-complex
Python fully supports mixed arithmetic: when a binary arithmetic
operator has operands of different numeric types, the operand with the
“narrower” type is widened to that of the other, where plain integer
is narrower than long integer is narrower than floating point is
narrower than complex.
So, 10 is widened to 10.0. Thats why 10 == 10.0
Because that's the way Python defines equality for floats and integers. If the float represents a whole number, it's equal to the integer representing the same number (and even has the same hash code). Note that Java does something to similar effect (even though == cannot be overloaded by classes in Java). 10.0 == 10 is true because == with mixed (numeric) arguments performs binary numeric promotion which turns the int 10 into the floating point number 10.0.
u can use
>>> 10 == 10.0
True
>>> 10 is 10.0
False
is is the identity comparison.
== is the equality comparison.
is means is same instance. It evaluates to true if the variables on either side of the operator point to the same object and false otherwise.
Python automatically type converts during comparisons if possible and sensible to do so.
>>> False == 0
True
>>> True == 1
True
>>> True == 0
False
>>> True == 22
False
Also illustrates this behaviour.

Subtract boolean from float in python [duplicate]

This question already has answers here:
Is False == 0 and True == 1 an implementation detail or is it guaranteed by the language?
(3 answers)
Closed 9 years ago.
Anyways when debuging my code I found statement that basically subtracted boolean from float.
Then I tried following in python console:
>>> 15.0 - True
14.0
>>> 15.0 - False
15.0
Can anyone explain to me:
Why subtracting booleans from numeric types is legal (the docs only state that you can do and, not and or on boolean values: http://docs.python.org/3/library/stdtypes.html#boolean-operations-and-or-not)
Has this any practical use?
It is legal, because bool is a subclass of int:
>>> bool.__bases__
(<type 'int'>,)
>>> True == 1
True
>>> False == 0
True
Yes, it has some practical application. For example it was possible to do something like that before ternary statement was introduced:
result = [value_if_false, value_if_true][condition]
Which basically does what would be done in this code:
if condition:
result = value_if_false
else:
result = value_if_true
Other practical usages are:
you can sum several checks / booleans to receive number of results equaling True,
you can multiply by the result of the check:
result = can_count_a * a + can_count_b * b
http://docs.python.org/3/library/stdtypes.html#boolean-values
Boolean values are the two constant objects False and True. They are used to represent truth values (although other values can also be considered false or true).
In numeric contexts (for example when used as the argument to an arithmetic operator), they behave like the integers 0 and 1, respectively.
not really nowadays, but you can write
result = numeric_value * a_bool (this one is used a lot, for example, in shader languages)
instead of
result = numeric_value if a_bool else 0
or
result = (value_if_false, value_if_true)[a_bool]
Don't do any of that though.
It's mostly what people with experience in lower-level languages expect, why take that away from them? In C, true and false are still macros for 1 and 0.
Before 2.3, there was no bool type in Python as well, so when it was introduced making it a subclass of int made sure no code was broken.
True evaluates to 1 and False evaluates to 0.
>>> True is 1
False
>>> True == 1
True
>>>
Bool is a subclass of int. As stated in PEP-285:
6) Should bool inherit from int?
=> Yes.
In an ideal world, bool might be better implemented as a separate
integer type that knows how to perform mixed-mode arithmetic.
However, inheriting bool from int eases the implementation enormously
(in part since all C code that calls PyInt_Check() will continue to
work -- this returns true for subclasses of int). Also, I believe
this is right in terms of substitutability: code that requires an int
can be fed a bool and it will behave the same as 0 or 1. Code that
requires a bool may not work when it is given an int; for example, 3 &
4 is 0, but both 3 and 4 are true when considered as truth values.
This isn't of any much practical use and there are other answers with sudo examples of using bools. I thought it would be good to have some real examples:
f,b="Fizz","Buzz"
print "\n".join([["",f,b,f+b][(x%3==0) + 2*(x%5==0)] or str(x) for x in range(1,101)])
The section in question:
["",f,b,f+b][(x%3==0) + 2*(x%5==0)]
The selection of the return each line is based on two boolean expressions, if both are true we get (True) + 2*(True) which evaluates to 4 which is a fizzbuzz. Not too hard to understand once you get used to the idea that True == 1 and False == 0
Further more keeping with the theme:
print '\n'.join(['Fizz'*(not i%3) + 'Buzz'*(not i%5) or str(i) for i in range(1, 101)])
This example relies on what happens when you multiply strings in python:
>>> "Noelkd" * False
''
And that not True evaluates to 0:
>>> not True == 0
True
Uses for this fall into two categories:
Making harder to read code.
Competing in code golf competitions.

Categories

Resources