1. Importing the NumPy library
import numpy as np
Imports the NumPy library as np for numerical computations and array manipulations.
2. Creating a NumPy array arr
arr = np.array([10, 20, 30, 40])
Creates a NumPy array named arr with elements [10, 20, 30, 40].
3. Creating a boolean mask to select elements greater than 15
mask = arr > 15
Compares each element of arr to 15 and creates a boolean array mask:
For 10 → False
For 20 → True
For 30 → True
For 40 → True
So, mask = [False, True, True, True].
4. Assigning the value 5 to elements of arr where mask is True
arr[mask] = 5
Uses boolean indexing to update elements of arr where mask is True.
Elements at indices 1, 2, and 3 (values 20, 30, 40) are replaced with 5.
Updated arr becomes [10, 5, 5, 5].
5. Calculating and printing the sum of updated arr
print(np.sum(arr))
Calculates the sum of the updated array arr:
10 + 5 + 5 + 5 = 25
Prints 25.
Final output:
25
Download Book - 500 Days Python Coding Challenges with Explanation
.png)

0 Comments:
Post a Comment