Finding the difference between consecutive numbers in a list (Python)

Given a list of numbers, I'm trying to write code that finds the difference between consecutive elements. For example, A = [1, 10, 100, 50, 40]therefore, the output of the function should be [0, 9, 90, 50, 10]. Here is what I have been trying to use recursion so far:

def deviation(A):
    if len(A) < 2:
        return
    else:
        return [abs(A[0]-A[1])] + [deviation(A[1: ])]

However, the output I get (using Example A above as an input) is [9, [90, [50, [10, None]]]]. How to format brackets correctly? (I tried to guess and check, but I’m the closest I got) And how to write it, where it subtracts the current element from the previous element without receiving an index error for the first element? I still want the first element of the output list to be null, but I don’t know how to do this using recursion and for some reason seems best to me.

+4
source share
6 answers

You can do:

[y-x for x, y in zip(A[:-1], A[1:])] 


>>> A = [1, 10, 100, 50, 40]
>>> [y-x for x, y in zip(A[:-1], A[1:])]
[9, 90, -50, -10]

, , , ( ), .

:

, , - .

  • A[:-1] : [1, 10, 100, 50]
  • A[1:] : [10, 100, 50, 40]
  • zip(A[:-1], A[1:]) [(1, 10), (10, 100), (100, 50), (50, 40)]
  • - .
+5

() - numpy diff:

>>> A = [1, 10, 100, 50, 40]
>>> np.diff(A)
array([  9,  90, -50, -10])

( ), .

+4
[abs(j-A[i+1]) for i,j in enumerate(A[:-1])]
+2

:

def deviation(A):
    yield 0
    for i in range(len(A) - 1):
        yield abs(A[i+1] - A[i])

:

>>> A = [3, 5, 2]
>>> list(deviation(A))
[0, 2, 3]

EDIT:. , :

def deviation(A):
    prev = A[0]
    for el in A:
        yield abs(el - prev)
        prev = el
+1

:

>>> A = [1, 10, 100, 50, 40]
>>> l=[A[0]]+A
>>> [abs(l[i-1]-l[i]) for i in range(1,len(l))]
[0, 9, 90, 50, 10]
+1

:

def deviation(A) :
    if len(A) < 2 :
        return []
    else :
        return [abs(A[0]-A[1])] + deviation(A[1:])

. [deviation(a[1: ])] [], , .

None, []. "" , None, return '

+1

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


All Articles