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

后端 未结 6 2134
忘掉有多难
忘掉有多难 2020-12-20 17:48

Given a list of numbers, I am trying to write a code that finds the difference between consecutive elements. For instance, A = [1, 10, 100, 50, 40] so the outp

6条回答
  •  北海茫月
    2020-12-20 18:09

    Actually recursion is an overkill:

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

    Example:

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

    EDIT: Yet, another, even simplier and more efficient solution would be this:

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

提交回复
热议问题