Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Verifying arithmetic sequence python

i'm just wondering how I could check to verify that a list of numbers is arithmetic or not using python, so whether there is a common number in between each item in the list.

like image 540
Belgin Fish Avatar asked Dec 12 '22 20:12

Belgin Fish


2 Answers

This is what I'd write:

all((i - j) == (j - k) for i, j, k in zip(l[:-2], l[1:-1], l[2:]))

You could probably make it more efficient by only computing the differences once, but if you're concerned about efficiency you'd use numpy and write:

np.all((a[:-2] - a[1:-1]) == (a[1:-1] - a[2:]))

or even (saving a slice):

np.all(a[:-2] + a[2:] == 2 * a[1:-1])

Probably the most concise method is to use numpy.diff, as it will automatically convert a list into a numpy array:

np.all(np.diff(l, 2) == 0)
like image 133
ecatmur Avatar answered Dec 31 '22 06:12

ecatmur


You can use numpy.diff if you have access to numpy:

>>> a = numpy.array(range(1, 15, 2))
>>> numpy.diff(a)
array([2, 2, 2, 2, 2, 2])

So you can do

>>> d = numpy.diff(a)
>>> not numpy.any(d-d[0])
True

or even better

>>> not numpy.any(numpy.diff(a, 2))
True
like image 34
Lev Levitsky Avatar answered Dec 31 '22 07:12

Lev Levitsky