w3resource

NumPy - Find maximum element in large array using For loop and optimization


NumPy: Performance Optimization Exercise-9 with Solution


Write a NumPy program to generate a large NumPy array and write a function to find the maximum element using a for loop. Optimize it using NumPy's built-in functions.

Sample Solution:

Python Code:

import numpy as np
# Generate a large NumPy array with random integers
large_array = np.random.randint(1, 1000000, size=1000000)

# Function to find the maximum element using a for loop
def find_max_with_loop(arr):
    max_element = arr[0]
    for element in arr:
        if element > max_element:
            max_element = element
    return max_element

# Find the maximum element using the for loop method
max_with_loop = find_max_with_loop(large_array)

# Find the maximum element using NumPy's built-in function
max_with_numpy = np.max(large_array)

# Display the results
print(f"Maximum element using for loop: {max_with_loop}")
print(f"Maximum element using NumPy: {max_with_numpy}")

Output:

Maximum element using for loop: 999997
Maximum element using NumPy: 999997

Explanation:

  • Importing numpy: We first import the numpy library for array manipulations.
  • Generating a large array: A large NumPy array with random integers is generated.
  • Defining the function: A function find_max_with_loop is defined to find the maximum element using a for loop.
  • Finding maximum with loop: The maximum element is found using the for loop method.
  • Finding maximum with numpy: The maximum element is found using NumPy's built-in np.max function.
  • Displaying results: The results from both methods are printed out.

Python-Numpy Code Editor: