Code Explanation:
1. Importing the NumPy library
import numpy as np
Imports the NumPy library as np for numerical operations and array handling.
2. Creating a NumPy array arr
arr = np.array([1, 2, 3, 4, 5])
Creates a NumPy array named arr with elements [1, 2, 3, 4, 5].
3. Creating a list of indices idx
idx = [0, 2, 4]
Creates a Python list idx containing indices [0, 2, 4].
These indices correspond to elements in arr at positions 0, 2, and 4.
4. Indexing arr with idx to create new_arr
new_arr = arr[idx]
Uses fancy indexing to select elements from arr at indices 0, 2, and 4.
new_arr contains [1, 3, 5].
Note: This creates a new array, a copy, not a view.
5. Modifying an element of new_arr
new_arr[1] = 99
Sets the element at index 1 of new_arr (which is currently 3) to 99.
Now, new_arr becomes [1, 99, 5].
Since new_arr is a copy, this does not modify the original arr.
6. Calculating and printing the sum of arr and new_arr
print(np.sum(arr) + np.sum(new_arr))
Calculates the sum of the original array arr: 1 + 2 + 3 + 4 + 5 = 15
Calculates the sum of the modified new_arr: 1 + 99 + 5 = 105
Adds the sums: 15 + 105 = 120
Prints 120.
Final output:
120
Download Book - 500 Days Python Coding Challenges with Explanation
.png)

0 Comments:
Post a Comment