Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a diff array using lambda functions in python

I wish to create a diff array in python as follows

>>> a = [1,5,3,8,2,4,7,6]
>>> diff = []
>>> a = sorted(a,reverse=True)
>>> for i in xrange(len(a)-1):
        diff.append(a[i]-a[i+1])

But I wanted to refactor the above code. I tried to achieve it using lambda functions. But failed to get the result.

>>> [i for i in lambda x,y:y-x,sorted(a,reverse=True)]

The above code returns

[<function <lambda> at 0x00000000023B9C18>, [1, 2, 3, 4, 5, 6, 7, 8]]

I wished to know can the required functionality be achieved using lambda functions or any other technique? Thanks in advance for any help!!

NOTES:

1) Array 'a' can be huge. Just for the sake of example I have taken a small array.

2) The result must be achieved in minimum time.

like image 548
SohamC Avatar asked Feb 12 '23 21:02

SohamC


1 Answers

If you can use numpy:

import numpy as np
a = [1,5,3,8,2,4,7,6]

j = np.diff(np.sorted(a))    # array([1, 1, 1, 1, 1, 1, 1])
print list(j)
# [1, 1, 1, 1, 1, 1, 1]

k =  np.diff(a)    # array([ 4, -2,  5, -6,  2,  3, -1])
print list(k)
# [4, -2, 5, -6, 2, 3, -1]

Timing comparisons with one-hundred-thousand random ints - numpy is faster if the data needs to be sorted:

from timeit import Timer
a = [random.randint(0, 1000000) for _ in xrange(100000)]
##print a[:100]
def foo(a):
    a = sorted(a, reverse=True)
    return [a[i]-a[i+1] for i in xrange(len(a)-1)]

def bar(a):
    return np.diff(np.sort(a))

t = Timer('foo(a)', 'from __main__ import foo, bar, np, a')
print t.timeit(10)
# 0.86916993838

t = Timer('bar(a)', 'from __main__ import foo, bar, np, a')
print t.timeit(10)
# 0.28586356791
like image 133
wwii Avatar answered Feb 15 '23 10:02

wwii