Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate difference between adjacent items in a python list

Tags:

python

list

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
like image 975
Martlark Avatar asked Aug 24 '11 09:08

Martlark


People also ask

How do you tell the difference between adjacent elements in an array?

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.

How do you find the difference between two numbers in a list Python?

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.

How do you find adjacent elements in a list?

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.


2 Answers

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.

like image 190
mtrw Avatar answered Oct 23 '22 00:10

mtrw


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...
like image 35
Mariy Avatar answered Oct 23 '22 01:10

Mariy