Check If All Numbers In A List Are Same Sign In Python?
Solution 1:
You can make use of all function: -
>>>x = [1, 2, 3, 4, 5]>>>all(item >= 0for item in x) orall(item < 0for item in x)
True
Don't know whether it's the most pythonic way.
Solution 2:
How about:
same_sign = not min(l) < 0 < max(l)
Basically, this checks whether the smallest element of l and the largest element straddle zero.
This doesn't short-circuit, but does avoid Python loops. Only benchmarking can tell whether this is a good tradeoff for your data (and whether the performance of this piece even matters).
Solution 3:
Instead of all you could use any, as it short-circuits on the first true item as well:
same = lambda s: any(i >= 0for i in s) ^ any(i < 0for i in s)
Solution 4:
Similarly to using all, you can use any, which has the benefit of better performance, as it will break the loop on the first occurrence of different sign:
defall_same_sign(lst):
if lst[0] >= 0:
returnnotany(i < 0for i in lst)
else:
returnnotany(i >= 0for i in lst)
It would be a little tricky if you want to consider 0, as belonging to both groups:
def all_same_sign(lst):
first=0
i =0
while first==0:
first= lst[i]
i +=1
if first>0:
returnnotany(i <0for i in lst)
else:
returnnotany(i >0for i in lst)
In any case, you iterate the list once instead of twice as in other answers. Your code has the drawback of iterating the loop in Python, which is much less efficient than using built-in functions.
Post a Comment for "Check If All Numbers In A List Are Same Sign In Python?"