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?
>Solution :
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