Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect alternating signs

Tags:

python

numpy

Is there a nice and short way to tell whether a python list (or numpy array) contains numbers with alternating signs? In other words:

is_alternating_signs([1, -1, 1, -1, 1]) == True
is_alternating_signs([-1, 1, -1, 1, -1]) == True
is_alternating_signs([1, -1, 1, -1, -1]) == False
like image 350
Boris Gorelik Avatar asked Jun 23 '11 08:06

Boris Gorelik


People also ask

How do you know if an array is alternating?

Skip the first element. For every other element, compare its sign with the sign of the previous element: If they're different, the sequence is still alternating upto now - you should continue. If they're the same sign, the sequence is not alternating.

Is alternating a sequence?

A sequence whose terms alternate in sign is called an alternating sequence, and such a sequence converges if two simple conditions hold: 1. Its terms decrease in magnitude: so we have .


1 Answers

OK, thanks to SO "related" feature. I found this question and adopted the answer by ianalis and the comment by lazyr

def is_alternating_signs(a):
    return numpy.all(numpy.abs(numpy.diff(numpy.sign(a))) == 2)



print is_alternating_signs([1, -1, 1, -1, 1]) 
print is_alternating_signs([-1, 1, -1, 1, -1]) 
print is_alternating_signs([1, -1, 1, -1, -1]) 

The output is

True
True
False
like image 68
Boris Gorelik Avatar answered Oct 01 '22 15:10

Boris Gorelik