Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Count Sign Change

I have this array:

X = [0,2,-1,2,1,2]

And the sign changes two times (0 is positive here).

Example:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading