python,arrays,performance,numpy , Find largest difference between adjacent floats in ordered array

## Question:

Tag: python,arrays,performance,numpy

Say I have an ordered array/list like this one:

``````a = [0.2, 0.35, 0.88, 1.2, 1.33, 1.87, 2.64, 2.71, 3.02]
``````

I want to find the largest difference between adjacent elements efficiently. In this case it would be `(2.64 - 1.87) = 0.77`.

I could use a `for` loop but I wonder if there's a more elegant/efficient solution. Solutions using `numpy` are welcomed.

TEST

OK, I took all the answers and tested them (see code at the bottom). These are the results in seconds:

``````0.0867638587952 0.118239144757 mark
0.00108003616333 0.118239144757 mtrw
0.0790281295776 0.118239144757 yurib
0.000712156295776 0.118239144757 elyase
``````

which means elyase is the winner by several orders of magnitude. Thank you all!

MWE:

``````import numpy as np
import time

a = np.sort(np.random.uniform(0., 1000., 100000))

tik = time.time()
val = max(y - x for x,y in zip(a, a[1:]))
print time.time() - tik, val, 'mark'

tik = time.time()
val = np.ediff1d(a).max()
print time.time() - tik, val, 'Padraic'

tik = time.time()
val = np.max(np.abs(np.diff(a)))
print time.time() - tik, val, 'mtrw'

tik = time.time()
val = max(a[i+1]-a[i] for i in range(len(a)-1))
print time.time() - tik, val, 'yurib'

tik = time.time()
val = np.diff(a).max()
print time.time() - tik, val, 'elyase'
``````

A numpy solution:

``````np.diff(a).max()
``````

# Related:

## Translating a character array into a integer string in C++

c++,arrays,string
I was trying to achieve translating a character array into a integer string and corresponding character to their alphabetical order. For instance: A(a) = 0 , Z(z) = 25. string key_char = argv[1]; string key_num; for (int i = 0; i < key_char.length(); i++){ if (isalpha(key_char[i])){ if (islower(key_char[i])){ key_num[i] =...

## Matplotlib: Plot the result of an SQL query

python,sql,matplotlib,plot
from sqlalchemy import create_engine import _mssql from matplotlib import pyplot as plt engine = create_engine('mssql+pymssql://**:****@127.0.0.1:1433/AffectV_Test') connection = engine.connect() result = connection.execute('SELECT Campaign_id, SUM(Count) AS Total_Count FROM Impressions GROUP BY Campaign_id') for row in result: print row connection.close() The above code generates an array: (54ca686d0189607081dbda85', 4174469) (551c21150189601fb08b6b64', 182) (552391ee0189601fb08b6b73', 237304) (5469f3ec0189606b1b25bcc0',...