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
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.
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 .
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With