NumPy: Place a specified element in specified time randomly in a specified 2D array
Place elements randomly in a 2D array.
Write a NumPy program to place a specified element in specified time randomly in a specified 2D array.
Pictorial Presentation:
Sample Solution:
Python Code:
# Importing the NumPy library
import numpy as np
# Defining variables n (size of the square array), i (number of random elements), and e (specified element)
n = 4
i = 3
e = 10
# Creating an array of zeros with shape (n, n)
array_nums1 = np.zeros((n, n))
# Displaying the original array of zeros
print("Original array:")
print(array_nums1)
# Putting the specified element 'e' in 'i' randomly chosen positions within the array
np.put(array_nums1, np.random.choice(range(n * n), i, replace=False), e)
# Displaying the array after placing the specified element 'e' in 'i' randomly chosen positions
print("\nPlace a specified element in specified time randomly:")
print(array_nums1)
Sample Output:
Original array: [[0. 0. 0. 0.] [0. 0. 0. 0.] [0. 0. 0. 0.] [0. 0. 0. 0.]] Place a specified element in specified time randomly: [[10. 0. 0. 0.] [10. 0. 0. 0.] [ 0. 0. 0. 10.] [ 0. 0. 0. 0.]]
Explanation:
In the above example -
Three variables 'n', 'i', and 'e' are assigned values 4, 3, and 10, respectively.
array_nums1 is initialized as a 2D NumPy array of zeros with shape (n, n), which in this case is (4, 4).
np.put(array_nums1, np.random.choice(range(n*n), i, replace=False), e):
In the above code -
- np.random.choice is used to randomly choose 'i' unique elements from the range of 0 to (n * n) - 1, i.e., 0 to 15.
- The parameter replace=False ensures that the elements are chosen without replacement, making them unique.
- np.put is used to replace the chosen elements in the flattened version of array_nums1 with the value 'e' (10).
Python-Numpy Code Editor:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics