I used the following script to try to answer this question:
def isEquilateral(x, y, z):
if x<0 or y <0 or z<0:
return False
elif x==y==z:
return True
else:
return False
It returned Private Test Cases, I don't know if this is a software bug, or my code really have some problem. Can anyone help? Thanks.
update 01
Question as below:
Write a function isEquilateral(x, y, z) that accepts the 3 sides of a triangle as arguments. The program should return True if it is an equilateral triangle.
Examples
>>> isEquilateral(2, 4, 3)
False
>>> isEquilateral(3, 3, 3)
True
>>> isEquilateral(-3, -3, -3)
False
While I'm not impressed with their feedback system, the problem is you return True when x, y, z == 0. A simpler solution:
def isEquilateral(x, y, z):
if x == y == z and x > 0:
return True
return False
And an even simpler solution, which shows off the beauty of Python (thanks, F.J!) using even more chained comparisons:
def isEquilateral(x, y, z):
return x == y == z > 0
This worked for me
def isEquilateral(x, y, z):
if (x == y or x == z) and x > 0:
return True
return False
This worked for me
def isEquilateral(x, y, z):
a = [x,y,z]
for e in a:
if e> 0:
if x==y==z:
return True
else:
return False
else:
return False
Related
This question already has answers here:
How does reduce function work?
(9 answers)
Closed 3 years ago.
>>> reduce(lambda x,y: x == y, [2,2,2,2,2])
False
I want to check every element in a list if they are the same and I thought this would do the trick, apprarently not. Can you some explain why it returns false and how should I fix it?
If you look at the docs,
reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates ((((1+2)+3)+4)+5)
So, a smaller example reduce(lambda x,y: x == y, [2,2,2]) would be (2==2)==2 would be False
The first application of the lambda function is 2 == 2, which yields True. The next application is True == 2, which is False. Finally, the last two applications of the lambda do False == 2, which is again False.
If the list has length >= 1, I would do:
all(lst[0] == x for x in lst)
In the lambda function you gives, x is the accumulated value, and y is each element in the array.
x: 2, y: 2, lambda returns True
x: True, y: 2, lambda returns False
...
x: False, y: 2, lambda returns False
To fix it, you could simple use len(set(arr)) == 1 to see if there is only one unique element in this array.
A simpler way to do this would be to check if the number of distinct elements in the list is 1
len(set([2,2,2,2,2]))==1
If you print the value of x and y during the reduce operation:
def f(x,y):
print 'x=',x,'y=',y
return x==y
print reduce(f, [2,2,2,2,2])
it outputs :
x= 2 y= 2
x= True y= 2 #x contains True because it is the result of (x==y) hence 2==2
x= False y= 2 #x contains False because it is the result of (x==y) hence True==2
x= False y= 2 #same reason
False
To avoid this behavior you could specify an initial element that contains the result of the reduction and the value of the previous element.
Something like
def f(x,y):
print 'x=',x, 'y=', y
return (x[1]==None or (x[0] and x[1]==y), y)
print reduce(f, [2,2,2,2,2], (True,None))
This time it outputs :
x= (True, None) y= 2
x= (True, 2) y= 2
x= (True, 2) y= 2
x= (True, 2) y= 2
x= (True, 2) y= 2
(True, 2)
In a compressed lambda form it boils down to:
reduce(lambda x,y: (x[1]==None or (x[0] and x[1]==y), y), list, (True,None))[0]
Try it
l = [2,2,2,2,2]
print reduce(lambda x,y: (x[1]==None or (x[0] and x[1]==y), y), l, (True,None))[0]
l = [2,2,3,2,2]
print reduce(lambda x,y: (x[1]==None or (x[0] and x[1]==y), y), l, (True,None))[0]
True
False
I am trying to program a recursive binary search algorithm in python. However, I keep running into an infinite while-loop. I am afraid that it must be something simple that I am overlooking, but I cannot find the answer anywhere, most questions about while-loops not terminating do use other conditions and not boolean values.
The algorithm does seem to work, it prints the index of the element that I am searching for, or "Value not found" when the element is not in the list. But the while loop does never terminates, Even though i set found = False after the value has been found/not found. Why is this?
def binarysearch(A, v, x, y):
found = True
while found:
if x < y:
h = (x+y) //2
if A[h] < v:
binarysearch(A, v, h+1, y)
else:
binarysearch(A, v, x, h)
elif A[x] == v:
found = False
print("Element you are looking for is at index {}".format(x))
else:
found = False
print("Value is not in array")
#Code to test the binarysearch algorithm
blist = []
for value in range(0,124):
if value % 2 ==0:
blist.append(value)
print(blist)
binarysearch(blist, 68, 0, len(blist)-1)
The found variable you are modifying with found = False is local to the scope of that particular recursive call to binarysearch. It is not the instance of found you are trying to modify, i.e. the one in the top level of the recursion tree. So although the while-loop in the current scope will terminate, the loops in the scopes above it will not.
Since you already have a mostly complete loop implementation, instead of using recursion on top of it (which is causing the scope-related error) you can just narrow the search range by overwriting x and y.
def binarysearch(A, v, x, y):
found = True
while found:
if x < y:
h = (x+y) //2
if A[h] < v:
x = h+1 // replaced
else:
y = h // replaced
elif A[x] == v:
found = False
print("Element you are looking for is at index {}".format(x))
else:
found = False
print("Value is not in array")
The mistake I made was that I used a while loop ON TOP OF the recursive calls, which basically are two ways of accomplishing the same. For the people interested in the algorithm that uses recursion instead of a while loop to keep it running, I provided a working version of it below.
def binarysearch(A, v, x, y):
if x < y:
h = (x+y) //2
if A[h] < v:
binarysearch(A, v, h+1, y)
else:
binarysearch(A, v, x, h)
elif A[x] == v:
print("Element you are looking for is at index {}".format(x))
else:
print("Value is not in array")
I have 2 variables, say x and y, and I need to check which of them is None
if x is None and y is None:
# code here
else:
if x is not None and y is not None:
# code here
else:
if x is None:
# code here
if y is None:
# code here
Is there a better approach to do this?
I am looking for a shorter IF ELSE structure.
Keeping the order you used:
if x is None and y is None:
# code here for x = None = y
elif x is not None and y is not None:
# code here for x != None != y
elif x is None:
# code here for x = None != y
else:
# code here for x != None = y
Modifying the order to reduce boolean evaluations:
if x is None and y is None:
# code here for x = None = y
elif x is None:
# code here for x = None != y
elif y is None:
# code here for x != None = y
else:
# code here for x != None != y
In a 4 case scenario, you should consider which of the options has a higher probability and which has the second higher and keep them the first two options, as this will reduce the amount of conditions checked during execution. The last two options will both execute the 3 conditions so the order of these two doesn't matter. For example the first code above considers that prob(x=None & y=None) > prob(x!=None & y!=None) > prob(x=None & y!=None) ~ prob(x!=None & y=None) while the second one considers that prob(x=None & y=None) > prob(x=None & y!=None) > prob(x!=None & y=None) ~ prob(x!=None & y!=None)
def func1(a):
print a
def func2(a):
print a
def func3(a):
print a
def func4(a):
print a
options = {(1, 1): func1,
(1, 0): func2,
(0, 1): func3,
(0, 0): func4,}
options[(True, True)](100)
output:
100
If you need 4 different paths for each of the possible combination of x and y, you can't really simplify it that much. That said, I would group the checks for one of the variables (i.e. check if x is None first, then inside, check if y is None.)
Something like this:
if x is None:
if y is None:
# x is None, y is None
else:
# x is None, y is not None
else:
if y is None:
# x is not None, y is None
else:
# x is not None, y is not None
you can start by using the elif statement, it will be a little bit shorter just like this:
if x is None and y is None:
# code here
elif x is not None and y is not None:
# code here
elif x is None:
# code here
if y is None:
# code here`
Assuming you need to have all 4 cases covered seperately:
if not x and not y:
# code here (both are none or 0)
elif not x
# code here (x is none or 0)
elif not y
# code here (y is none or 0)
else
#code here (both x and y have values)
This would be the shortest way to handle it, but doesn't only check for None/Null values. not x returns true for anything falsey, such as empty strings, False, or 0.
If you have two booleans, there are four distinct possibilities: 00 01 10 and 11. If in each case something distinctly different is supposed to happen, there is not really something that could reduce the number of tests.
Having said that, in some comparable cases pattern matching might feel more straightforward. I don't know about that in Python though.
The below logic should run for all the combination. Write in your language
if (x is not null and y is not null){
//code here
}
else if(x is null and y is not null){
//code here
}
else if(x is not null and y is null){
//code here
}
else
{
//Code here
}
The C Code for the same:
int main()
{
int x,y;
printf("Enetr Two Number");
scanf("%d%d",&x,&y);
if(x!=NULL && y!=NULL)
printf("X and Y are not null");
else if(x==NULL && y!=NULL)
printf("X is null and Y is not null");
else if(x!=NULL && y==NULL)
printf("X is not null and Y is null");
else
{
printf("The value of x and y are null");
}
}
I have a set of three variables x, y, z and I want to check if they all share the same value. In my case, the value will either be 1 or 0, but I only need to know if they are all the same. Currently I'm using
if 1 == x and 1 == y and 1 == z:
sameness = True
Looking for the answer I've found:
if 1 in {x, y, z}:
However, this operates as
if 1 == x or 1 == y or 1 == z:
atleastOneMatch = True
Is it possible to check if 1 is in each: x, y, and z?
Better yet, is there a more concise way of checking simply if x, y, and z are the same value?
(If it matters, I use Python 3.)
If you have an arbitrary sequence, use the all() function with a generator expression:
values = [x, y, z] # can contain any number of values
if all(v == 1 for v in values):
otherwise, just use == on all three variables:
if x == y == z == 1:
If you only needed to know if they are all the same value (regardless of what value that is), use:
if all(v == values[0] for v in values):
or
if x == y == z:
To check if they are all the same (either 1 or 2):
sameness = (x == y == z)
The parentheses are optional, but I find it improves readability
How about this?
x == y == z == 1
In my case, the value will either by 1 or 2, but I only need to know if they are all the same
Is it possible to check if 1 is in each: x, y, and z?
Better yet, is there a more concise way of checking simply if x, y, and z are the same value?
Sure:
x == y == z
which is equivalent to
(x == y) and (y == z)
If you have an arbitrary (nonzero) number of values to compare:
all(values[0] == v for v in values[1:])
You could use something similar to what you have:
sameness = (len({x, y, z}) == 1)
This allows for any number of variables. For example:
variables = {x, y, z, a, b, ...}
sameness = (len(variables) == 1)
Note: Creating a set means that each variable needs to be hashed and the hashed values need to be stored, but all() with a generator expression is short-circuiting and keeps track of only two values at a time. Therefore, besides its readability, the generator expression is more efficient.
Another way:
sameness = all(e == 1 for e in [x, y, z])
[x,y,z].count(1)
will count how many variables have 1 as value
Below all() and any() functions in python can server the purpose.
all() act as "AND": if all the values in any ittertable object is equal to given condition value, then Return True else return False.
Examples
assert all(b == True for b in [True,True,True,True]) == True
assert all(b == True for b in [False,True,True,True]) == False
any() act as "OR": if any one value in any ittertable object is equal to given condition value, then Return True else return False.
Examples
assert any(b == True for b in [False,False,False,True]) == True
assert any(b == True for b in [False,False,False,False]) == False
If you had more variables, this way might be most concise:
{x} == {y, z}
(Not as fast as x == y == z, but the question asked for concise, not for fast.)
Is there any computational difference between these two methods of checking equality between three objects?
I have two variables: x and y. Say I do this:
>>> x = 5
>>> y = 5
>>> x == y == 5
True
Is that different from:
>>> x = 5
>>> y = 5
>>> x == y and x == 5
True
What about if they are False?
>>> x = 5
>>> y = 5
>>> x == y == 4
False
And:
>>> x = 5
>>> y = 5
>>> x == y and x == 4
False
Is there any difference in how they are calculated?
In addition, how does x == y == z work?
Thanks in advance!
Python has chained comparisons, so these two forms are equivalent:
x == y == z
x == y and y == z
except that in the first, y is only evaluated once.
This means you can also write:
0 < x < 10
10 >= z >= 2
etc. You can also write confusing things like:
a < b == c is d # Don't do this
Beginners sometimes get tripped up on this:
a < 100 is True # Definitely don't do this!
which will always be false since it is the same as:
a < 100 and 100 is True # Now we see the violence inherent in the system!
Adding a little visual demonstration to already accepted answer.
For testing equality of three values or variables. We can either use:
>>> print(1) == print(2) == print(3)
1
2
3
True
>>> print(1) == print(2) and print(2) == print(3)
1
2
2
3
True
The above statements are equivalent but not equal to, since accesses are only performed once. Python chains relational operators naturally. See this docs:
Comparisons can be chained arbitrarily, e.g., x < y <= z is equivalent to x < y and y <= z, except that y is evaluated only once (but in both cases z is not evaluated at all when x < y is found to be false).
If the functions called (and you are comparing return values) have no side-effects, then the two ways are same.
In both examples, the second comparison will not be evaluated if the first one evaluates to false. However: beware of adding parentheses. For example:
>>> 1 == 2 == 0
False
>>> (1 == 2) == 0
True
See this answer.