Belgin Fish Belgin Fish - 4 months ago 9
Python Question

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.


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)