I am doing Grok Learning Course, and have come across a problem. Sorry if I have done anything badly; not a professional at coding:
I am trying to make a variable that will be True/False depending on many conditions:
So,
x = True if y > 2 , g < 4 , n != 3
I have tried different ways to do this like:
Assigning variable to each of my conditions:
if y > 2:
ytrue = True
etc..
However, I want to find a better way of doing it than that, which is long and tedious.
Thankyou.
It's as simple as
x = y > 2 and g < 4 and n != 3
which evaluates to True if all three conditions hold and False otherwise.
As you are new to programming, here's how you read it.
First you evaluate the right hand side which is
y > 2 and g < 4 and n != 3
This is evaluated left to right. First it evaluates y > 2 which will either be True or False. If False the whole right hand side is False and False will be assigned to x. Otherwise it keeps on evaluating all of the other sub-expressions on the right hand side until one of them is False or until you've found every one to be True, in which case the whole right hand side is True.
In either case, True or False, your variable x gets the desired value.
x = y > 2 and g < 4 and n != 3
If you have multiple expressions and if you want to do expression on a expression using and's & or's combinations its better to put it on like this
x= ((y > 2 and g < 4) or n != 3)
Comparison operators like (>, <, !=, etc.) all end up being evaluated down to True or False by the python interpreter.
Python also has Boolean the operators and, or, not (Read more in Section 4.2 of the python docs) but you can use these in combination with the comparison operators to chain them. So your assignment becomes:
x = y > 2 and g < 4 and n != 3
You can use ternary conditional operator :
['false','true'][y > 2 and g < 4 and n != 3]
How it works ?
True == 1, False == 0
because booleans are a subclass of int , so [y > 2 and g < 4 and n != 3] produce a integer value but ['false','true'] takes it as index value.
True gives ['false','true'][1]
And False gives ['false','true'][0]
Test case:
y=4
g=1
n=3
print(['false','true'][y > 2 and g < 4 and n != 3])
output:
false
Test case2:
y=4
g=1
n=1
print(['false','true'][y > 2 and g < 4 and n != 3])
output:
true
Now, if you want you can store the result in a variable :
x=['false','true'][y > 2 and g < 4 and n != 3]
which you wanted i think.
Related
What does the minus sign do, inside the following list comprehension?
[n for n in range(1000) if n % 9 == 0 - n % 4 == 0]
This produces a list of multiples of 36 (between 0 and 1000), so the minus sign appears to be functioning like "and". But if you pick n to be a multiple of 36, both n % 9 == 0 and n % 4 == 0 would be True and therefore the literal subtraction of those two would be 0, which I assume Python would interpret as False and therefore exclude n from the list.
I'd never seen the minus sign used in this context like this before, so I'm wondering what's going on here.
Just use n % 36 == 0 instead.
Edit: Just realized the below is wrong.
This code is really weird, so I guess I just subconsciously assumed it was normal. I'm keeping the text below because it's a cool fact I didn't know before.
As far as I can tell, this behaves like the bitwise XOR operator. It returns True (includes n) if one and only one condition is True:
print(True - False) # 1
print(False - True) # -1 (which is a True value)
print(True - True) # 0
print(False - False) # 0
# bool(A - B)
# A B -> _True__False_
# True | False True
# False | True False
# This is an XOR gate.
You could also use ^.
Today I was browsing through a coding website and found a simple code in Python which I was having a hard time to comprehend.
Below is the exact code (with extra details added as comments):
x = -23
sign = [1,-1][x < 0] # -1 if x is negative and 1 if x is positive
print(sign) #outputs -1 since x=-23 is negative
Can anyone please help me understand how this code is working and what this technique is called (I presume it is some kind of list comprehension/manipulation)?
This is playing with the fact that True is equivalent to 1 and False to 0.
If x<0 returns True, then [1,-1][x < 0] is equivalent to [1,-1][1], and thus -1.
The logic is the same when x<0 returns False: [1,-1][0] -> 1
sign = [1,-1][x < 0] is just a fancy way to write
if x < 0:
sign = -1
else:
sign = 1
x < 0 is either True or False. Since True == 1 and False == 0 you can use booleans to index into the list [-1, 1].
x = -23
x2 = 23
sign = ["false","true"][x > 0]
sign2 = ["false","true"][x2 > 0]
print("sign:",sign)
print("sign2:",sign2)
the result is sign:false,sign2:true
I was wondering how to have an if statement in python that will react to any 3 out of 5 conditions being true to make the if statement true.
if (a>2) and (b>3) and (c>2) and (d>6) and (e>4):
list.append(True)
This code would add true to the array "list" if all 5 conditions are met but I was wondering how to get it to work if any 3 of the 5 are true to then append true to "list"?
How about this?
values = [a>2, b>3, c>2, d>6, e>4]
if sum(values) >= 3:
list.append(True)
Just copying what #Blckknght said in the comments b/c I can't explain it better. This works because:
True is equal to 1 and False is equal to 0 (the bool class is a subclass of int)
sum sums numbers, so you check for a sum of booleans >= 3!
Similar to #Tom 's answer but with using tuples that leads to (maybe) faster construction, garbage collection and (maybe) a nicer syntax.
if sum((a > 2, b > 3, c > 2, d > 6, e > 4)) >= 3:
lst.append(True)
I have a control statement as following:
if x < 0 or x >= ht or y < 0 or y >= wdt:
im_warped[i][j] = 0
else:
im_warped[i][j] = im[x][y]
which gives the same result as following:
if 0 < x < ht and 0 < y < wdt:
im_warped[i][j] = im[x][y]
I am not specifying an else case for the second control statement, eventhough I am sure that such values (exceeding the bounds) do exist. So what exactly is happening here? Do they automatically get assigned to zero / null values (which I think is unlikely)
If you don't have an else block, then nothing else will happen to the data. Your im_warped array will only have an entry modified in accordance with your if statement
The answer to your question, then, depends on what happens to that data before reaching this if statement. If it's a numpy array created with np.zeros, then all of its entries are 0 by default. If it's data that you're getting from somewhere else, those default values could be anything and depend on what the input data looks like.
if statements have blocks, not values. You seem to be confusing this with the ternary operator. For instance, in Tableau, if you write
if condition then
x
else
y
end
then when condition is true, this whole statement will be evaluated as having the value of x. If you write
z = if condition then x else y end
then whenever condition is true, the expression if condition then x else y will be evaluated as being x, and so x will be assigned to z.
In Python, however, if you write
if condition then:
x
Python expects x to not be a value, but an instruction. In your first example, you had im_warped[i][j]=0. This is an instruction: it tells Python to assign 0 to im_warped[i][j]. If you were to write
z = if condition:
x
else:
y
that will return an error in Python, because in Python if-then-else is not the ternary operator, it's a control statement. It does not return any values, conditional or default. Rather, it runs code. The "default", to the extent there is one, is to not run any code. When you wrote if x < 0 or x >= ht or y < 0 or y >= wdt: im_warped[i][j] = 0, it is not the if-then-else statement that is returning a value; you are putting a value of 0 within the code that it is running.
There is a ternary operator in Python, but its syntax is slightly different: it is conditional_result if condition else default. So your first example could be written as
im_warped[i][j] = 0 if x < 0 or x >= ht or y < 0 or y >= wdt else im[x][y]
and if you were to write
im_warped[i][j] = im[x][y] if 0 < x < ht and 0 < y < wdt
without an else, that would return an error.
I'm trying to find minimum element in matrix row, but there are two conditions:
1) it must be > 0
2) and this point must be not visited(is_visited[k] is False)
I'm trying to do next:
min(x for x in matr_sum[i] if x > 0 if is_visited[k] is False )
But there is an error: min() arg is an empty sequence
The full block of code:
for k in range(4):
if matr_sum[i][k] == min(x for x in matr_sum[i] if x > 0 if is_visited[k] is False ) and i!=k:
return k
How to resolve it? Or should I write my min() function? Because it works with one condition:
min(x for x in matr_sum[i] if x > 0)
But with two conditions, it doesn't work.
If you want to avoid this ValueError in general, you can set a default argument to min(), that will be returned in case of an empty list. See described here.
min([], default="EMPTY")
# returns EMPTY
Note that this only works in Python 3.4+
There is no problem with the syntax. It's certainly unusual to have two if clauses, but it's allowed. Consider:
print(min(x for x in range(1,300) if x % 3 == 0 if x % 5 == 0))
Output:
15
However:
print(min(x for x in range(1,300) if x % 2 != 0 if x % 2 != 1))
Output:
ValueError: min() arg is an empty sequence
There are no integers that are both odd and even, so there are no values for min to see, so it throws an exception.
I deduce that in your code, there are no values that pass both conditions. Python doesn't allow you to compute "the minimum of no values", mainly because it makes no sense.
You have to decide what you want to do in the case where there is no minimum because there are no values greater than 0. For example, if you don't want to return k in that case then I might re-write your code something like this:
for k in range(4):
if k != i and is_visited[k] is False:
if matr_sum[i][k] > 0 and matr_sum[i][k] == min(x for x in matr_sum[i] if x > 0):
return k
It might not be obvious why this helps, but assuming matr_sum[i] is a list or similar, then once we know matr_sum[i][k] > 0 then we know the generator passed to min isn't empty, so we won't get an exception. Whereas if matr_sum[i][k] <= 0, then it certainly isn't equal to the smallest positive value, so there's no need to compute the min at all. Another way to write that would be:
if matr_sum[i][k] > 0 and not any(0 < x < matr_sum[i][k] for x in matr_sum[i])
Actually, I'd normally write if not is_visited[k], but I leave it as is False since I don't know whether changing it would change the behaviour of your code.
Try this - it creates the list of x values xs and then only tries to find the min if xs is non-empty. You may need to add some logic to handle the case that xs is empty, depending on what your code is doing.
for k in range(4):
if is_visited[k] is False and i != k:
xs = [x for x in matr_sum[i] if x > 0]
if xs and matr_sum[i][k] == min(xs):
return k
Just use and operation for concatenate tow if statement :
min(x for x in matr_sum[i] if x > 0 and if is_visited[k] is False and i!=k)