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)
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
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