I have this array:
X = [0,2,-1,2,1,2]
And the sign changes two times (0 is positive here).
Example:
2 to -1 (first time)
-1 to 2 (second times)
last_sign = 1
sign_changes = 0
for x in X:
if x == 0:
sign = -1
else:
sign = x / abs(x)
if sign == -last_sign:
sign_changes = sign_changes 1
last_sign = sign
print(sign_changes)
But when I print the result I get 4. Why?
CodePudding user response:
Unlike what you described, you are assigning negative sign to zero: note that you put sign = -1
at if x == 0:
. This is the culprit here. (Also your current code assumes that the list starts with a non-negative number. A list starting with a negative number won't produce an expected outcome.)
You can try instead:
X = [0,2,-1,2,1,2]
print(sum((a >= 0) != (b >= 0) for a, b in zip(X, X[1:]))) # 2
CodePudding user response:
My suggestion, iterate pairwise and check if the pairs have different signs:
from itertools import tee
def pairwise(iterable):
# pairwise('ABCDEFG') --> AB BC CD DE EF FG
a, b = tee(iterable)
next(b, None)
return zip(a, b)
X = [0, 2, -1, 2, 1, 2]
res = sum((before < 0) ^ (after < 0) for before, after in pairwise(X))
print(res)
Output
2
As an alternative, without any libraries, use:
res = sum((before < 0) ^ (after < 0) for before, after in zip(X, X[1:]))
The expression:
(before < 0) ^ (after < 0)
is an exclusive or, it will only be True (1) if the boolean values are different.