Creating a diff array using lambda functions in python

I want 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 reorganize the above code. I tried to achieve this using lambda functions. But the result did not work out.

>>> [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 wanted to know if the required functions can be implemented using lambda functions or any other technique? Thanks in advance for any help!

NOTES:

1) The array 'a' can be huge. For an example I took a small array.

2) The result should be achieved in the shortest time.

+4
source share
4 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]

100- ints-numpy , :

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
+3

, :

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

, , . , lambda:)

:

Mine:

1.59740447998e-05

@Marcin-

0.00110197067261

@roippi-

0,000382900238037

@

+0,00154685974121

, , @roippi, @Marcin, @wwi.

P.S. , time.time() time.time().

+3

:

diff = [v[0] - v[1] for v in zip(sorted(a,reverse=True)[0:-1], sorted(a,reverse=True)[1:])]

#gives: diff = [1, 1, 1, 1, 1, 1, 1]

. , .

@aj8uppal , , :

a = sorted([1,5,3,8,2,4,7,6], reverse=True)
diff = [v[0] - v[1] for v in zip(a[0:-1], a[1:])]    
#gives: diff = [1, 1, 1, 1, 1, 1, 1]
+1
a = [1,5,3,8,2,4,7,6]
a = sorted(a,reverse=True)

There is no way to improve these lines. You need to transform your data by sorting it, without any sense of changing what you have done.

from itertools import izip, starmap

from operator import sub

list(starmap(sub,izip(a,a[1:])))
Out[12]: [1, 1, 1, 1, 1, 1, 1]

If areally massive, you can replace the fragment a[1:]with isliceto save memory overhead:

list(starmap(sub,izip(a,islice(a,1,None))))

Although, if this is true, you should probably use it numpy.

np.diff(a) * -1
Out[24]: array([1, 1, 1, 1, 1, 1, 1])
+1
source

Source: https://habr.com/ru/post/1542271/


All Articles