This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 1 year ago.
The code below works such that an array is an input in a function. This 2 element array is iterated such that it would stop if the difference between the new and previously iterated array values equals zero (or it is intended to work as such). Note that the function below is just a pseudo function.
Is using a "OR" and "AND" operator appropriate for what I want. If so, which is best to use and if not, what is a better method?
def func(array):
counter = 0
diff = True
array_i = array
while diff:
array_f = array_i + 1/array_i
diff = abs(array_i[0] - array_f[0]) or abs(array_i[1] - array_f[1]) > 0
array i = array_f
counter += 1
return array_i, counter
The logical operator or is used when you want to check a condition or another condition. The and operator is when both are to be combined.
Checks to see if either one or the other are greater than zero.
abs(array_i[0] - array_f[0]) > 0 or abs(array_i[1] - array_f[1]) > 0
checks to see if both are greater than zero.
abs(array_i[0] - array_f[0]) > 0 and abs(array_i[1] - array_f[1]) > 0
Related
This question already has answers here:
Python: max/min builtin functions depend on parameter order
(3 answers)
Closed 3 years ago.
Can anyone tell me why looking for the minimum value in a list using min(list) is not working when NaN is the first element of the list? The same applies when using max(list)
import math
y = [float('nan'),1,2,3,0,float('nan'),6,7,8,9]
print(y)
print(math.isnan(y[0]))
print(min(y))
w = [10,1,2,3,0,float('nan'),6,7,8,9]
print(w)
print(min(w))
print(math.isnan(w[5]))
Any comparison operation performed on nan with a number will return False.
print(y[1] > y[0])
print(y[1] < y[0])
Results in
False
False
If the built-in function follows the same logic while comparing the elements the above behavior is easily explained. If the first element is selected as min element any comparison afterward will be False hence returning nan as min element.
You can filter y or w to ignore nan:
print(min(i for i in y if not math.isnan(i)))
# 0
This question already has answers here:
Pythonic way of checking if a condition holds for any element of a list
(3 answers)
Closed 4 months ago.
Suppose I have n values in a list x = [1.2, -0.4, 3.5, ....]
I need to check if at least one of them is below zero.
So basically, if I had only two values, I'd have written
if x[0]< 0 or x[1] < 0
But now, I need to use the same or operator within a loop so as to check each one of the values in the list.
The command any(x) < 0 seems to return False every single time.
How would I have to go about it?
any is not vectorized. You'd have to apply it on each object in x:
any(n < 0 for n in x)
n < 0 for n in x creates a generator that yields one value at a time from x, and is quite efficient since it is short-circuited, meaning it will break (and return True) as soon as it finds the first n that is < 0.
You can also use numpy for vectorized operations
import numpy as np
x = np.array([1.2, -0.4, 3.5,0])
x<=0 # will return the array of boolean values
If you just need to check if the condition met or not then
any(x<=0) # will return true if array contains atleast one True
When using any() or all() the pc will check if the elements in the iterableare True or False. Thus, you need to add a list comprehension to create the iterable:
any([elt < 0 for elt in x])
Basically you need to do the following:
any(value < 0 for value in X)
You can find a detailed explanation here
This question already has answers here:
How does a for loop evaluate its argument
(3 answers)
Closed 6 years ago.
counter = Counter()
// fill data into counter
for a, b in counter.most_common():
if (b > 1):
counter[a] = np.log(b)
else:
counter[a] = -np.log((1 / (b+0.01)))
As I see, this is safe, based on my trial. No bad thing happens when I change the collection while I am enumerating it. In other languages, in each cycle of the for, the counter.most_common() value is evaluated.
Doesn't this happen in Python as well?
No, it doesn't. A more illustrative example:
def example():
print("Ping")
return [1,2,3,4]
for x in example():
print(x)
Output:
Ping
1
2
3
4
This question already has answers here:
Check if all values in list are greater than a certain number
(9 answers)
Closed 6 years ago.
I am doing this following:
if ycoords[0] > 0 and ycoords[1] > 0 and ycoords[2] > 0:
# do stuff
Can you shorten this code by doing something like:
if (ycoords[0] and ycoords[1] and ycoords[2]) > 0:
# do stuff
Yes, you could use all:
if all(x > 0 for x in ycoords):
or ycoords[:3] if ycoords has more than 3 elements.
No, you can however simply use min to simplify the test syntactically:
if min(ycoords[0],ycoords[1],ycoords[2]) > 0:
# do stuff
and given that ycoords exactly has three elements, even shorter:
if min(*ycoords) > 0:
#do stuff
you can here, as #Tagc says, omit the asterisk (*):
if min(ycoords) > 0:
#do stuff
but this will result in some overhead.
Another option is to use an all:
if all(x > 0 for x in [ycoords[0],ycoords[1],ycoords[2]]):
# do stuff
or again, if ycoords contains only these three elements:
if all(x > 0 for x in ycoords):
# do stuff
Something that is not intuitive is that and:
"neither and nor or restrict the value and type they return to False and True, but
rather return the last evaluated argument"
Just open a python terminal and do:
>> 4 and 3
3
Why is this important to take in account?
You might think that:
(ycoords[0] and ycoords[1] and ycoords[2]) > 0
is equivalent to:
ycoords[0] > 0 and ycoords[1] > 0 and ycoords[2] > 0
or that is equivalent to:
(bool(ycoords[0]) and bool(ycoords[1]) and bool(ycoords[2])) > 0
but it's instead equivalent to:
ycoords[2] > 0
So, be careful because the interpreter is not doing what you think is doing.
This question already has answers here:
Pythonic way of checking if a condition holds for any element of a list
(3 answers)
Closed 8 years ago.
how do you detect if a value held in a list is negative, I just need to find out if there is a value that is negative, so far i have this:
if list[range(list)] < 0
But surely this will only detect if all the values in list are negative.How would i go about doing this?
Also, how would i be able to detect if a value in the list was not an integer, for example it was a floating point number, or even a character
Thanks
You can use any function, like this
if any(item < 0 for item in my_list):
For example,
print any(item < 0 for item in [0, 1, 2])
# False
print any(item < 0 for item in [0, 1, -2])
# True
We use a generator expression in the any function. It returns True, if any of the item is lesser than 0.