import numpy
def a(m, n):
array = numpy.zeros((m, n))
for i in range(m):
for j in range(n):
array[i, j] = i * j
return array
def main():
m = 3
n = 4
array = a(m, n)
print(array)
if __name__ == "__main__":
main()
Import statement
import numpy
This line imports the numpy library so that we can use numpy arrays and its associated functions.
Function definition:
def a(m, n):
array = numpy.zeros((m, n))
for i in range(m):
for j in range(n):
array[i, j] = i * j
return array
def a(m, n):
This defines a function named a that takes two parameters, m and n. These parameters are integers that specify the size of the 2D array: m is the number of rows and n is the number of columns.
array = numpy.zeros((m, n))
Here we create a numpy array of shape (m, n) filled with zeros. By default, numpy.zeros will create an array of type float64, which aligns with the requirement to store floating-point numbers.
Nested for loops:
for i in range(m):
for j in range(n):
array[i, j] = i * j
We iterate over each row i from 0 to m - 1, and each column j from 0 to n - 1.
(i, j) in the array, we assign the value i * j.i and column j will literally hold the product of the row index and the column index.return array
After filling the entire 2D array, we return it to wherever the function a was called.
Main function:
def main():
m = 3
n = 4
array = a(m, n)
print(array)
main() that does the following:
m = 3 and n = 4.a(m, n), which returns a 2D array with shape (3, 4) where each element at position (i, j) is i * j.array.array to the console.Condition to run main():
if __name__ == "__main__":
main()
This is a common Python idiom to ensure that main() is executed only if the script is run directly (not imported as a module by another script).
When main() is called:
m is set to 3, and n is set to 4.a(3, 4) creates an array with 3 rows and 4 columns (all zeros initially).(i, j) with the product i * j. This means:
i = 0, so every product 0 * j is 0 → [0, 0, 0, 0].i = 1, so elements become [1 *0, 1 * 1, 1 * 2, 1 * 3] → [0, 1, 2, 3].i = 2, so elements become [2 * 0, 2 * 1, 2 * 2, 2 * 3] → [0, 2, 4, 6].Thus, the resulting 2D array is:
[[0. 0. 0. 0.]
[0. 1. 2. 3.]
[0. 2. 4. 6.]]