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]
Solution
Try the exercise on your own first, then compare with the worked solution below.
# Solutionimport numpy as npdef 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 arrayexample_array = np.array([10, 20, 30, 40, 50])# Apply the functionresult = difference_and_append_prepend(example_array)print(result)
ModuleNotFoundError: No module named 'numpy'
Source Code
---title: "Review: NumPy Difference"subtitle: "Module 4: IDEs & Tools"format: html---## NumPy DifferenceWrite 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]::: {.callout-tip collapse="true"}## SolutionTry the exercise on your own first, then compare with the worked solution below.```{python}# Solutionimport numpy as npdef 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 arrayexample_array = np.array([10, 20, 30, 40, 50])# Apply the functionresult = difference_and_append_prepend(example_array)print(result)```:::