I have a list of millions of numbers. I want to find out if the difference between each number in the ordered list is the same for the entire list.
list_example = [ 0, 5, 10, 15, 20, 25, 30, 35, 40, ..etc etc etc]
What's the best way to do this?
My try:
import collections
list_example = [ 0, 5, 10, 15, 20, 25, 30, 35, 40 ]
count = collections.Counter()
for x,y in zip(list_example[0::],list_example[1::]):
print x,y,y-x
count[y-x] +=1
if len( count ) == 1:
print 'Differences all the same'
Result:
0 5 5
5 10 5
10 15 5
15 20 5
20 25 5
25 30 5
30 35 5
35 40 5
Differences all the same
Approach used in the below program is as followsTake its initial value as Arr[1]-Arr[0]. Start the loop, from the second element till last element index of array. If the calculated difference between Arr[i+1]-Arr[i]>MaxD, update MaxD . Continue this till we reach the second last element index.
Use set. difference() to Find the Difference Between Two Lists in Python. The set() method helps the user to convert any iterable to an iterable sequence, which is also called a set. The iterables can be a list, a dictionary, or a tuple.
The elements are iterated over using 'enumerate' and depending on the value of the index, the output is determined. If index value is 0, the element in first index is appended to the empty list. If index is equal to length of list minus 1, the element in previous index is appended to empty list.
Using pure Python:
>>> x = [0,5,10,15,20]
>>> xdiff = [x[n]-x[n-1] for n in range(1,len(x))]
>>> xdiff
[5, 5, 5, 5]
>>> all([xdiff[0] == xdiff[n] for n in range(1,len(xdiff))])
True
It's a little easier, and probably faster, if you use NumPy:
>>> import numpy as np
>>> xdiff = np.diff(x)
>>> np.all(xdiff[0] == xdiff)
True
But both of these create two extra lists (or arrays, in the case of NumPy) which may gobble up your available memory if you have millions of numbers.
The straight approach here is the best:
x = s[1] - s[0]
for i in range(2, len(s)):
if s[i] - s[i-1] != x: break
else:
#do some work here...
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