Review: NumPy Difference

Module 4: IDEs & Tools

NumPy Difference

Write a NumPy program to calculate the difference between neighboring elements, element-wise, and prepend [0, 0] and append [200] to a given array.

Example:

  • Input: [1, 3, 5, 7, 0]
  • Output: [ 0, 0, 2, 2, 2, -7, 200]

Try the exercise on your own first, then compare with the worked solution below.

# Solution
import numpy as np

def difference_and_append_prepend(arr):
  """
  Calculate the difference between neighboring elements, element-wise,
  and prepend [0, 0] and append [200] to the given array.
  """
  # Calculate differences
  diff = np.diff(arr, n=1)

  # Prepend [0, 0] and append [200]
  result = np.concatenate(([0, 0], diff, [200]))

  return result

# Example array
example_array = np.array([10, 20, 30, 40, 50])

# Apply the function
result = difference_and_append_prepend(example_array)
print(result)