w3resource

NumPy: Find the maximum and minimum value of a given flattened array


1. Maximum and Minimum of Flattened Array

Write a Python program to find the maximum and minimum value of a given flattened array.

Sample Solution:

Python Code:

# Importing the NumPy library
import numpy as np

# Creating a 2x2 array 'a' using arange and reshape
a = np.arange(4).reshape((2, 2))

# Displaying the original flattened array 'a'
print("Original flattened array:")
print(a)

# Finding and displaying the maximum value of the flattened array 'a' using np.amax()
print("Maximum value of the above flattened array:")
print(np.amax(a))

# Finding and displaying the minimum value of the flattened array 'a' using np.amin()
print("Minimum value of the above flattened array:")
print(np.amin(a)) 

Sample Output:

Original flattened array:
[[0 1]
 [2 3]]
Maximum value of the above flattened array:
3
Minimum value of the above flattened array:
0 

Explanation:

In the above exercise –

a = np.arange(4).reshape((2,2)): This line creates a 2D array of shape (2, 2) using the np.arange function and then reshape it to the desired shape using the reshape method.

np.amax(a): This code returns the maximum value of the entire array, which is 3.

np.amin(a): This code returns the minimum value of the entire array, which is 0.


For more Practice: Solve these Related Problems:

  • Create a function that flattens any multidimensional array and returns both the maximum and minimum values using vectorized operations.
  • Implement an algorithm that computes the maximum and minimum of a flattened array by first sorting it and then selecting the first and last elements.
  • Design a solution that finds the max and min values without using np.max or np.min by leveraging np.reduce or np.accumulate.
  • Develop a program that flattens an array and returns the difference between its maximum and minimum values.

Go to:


Previous: NumPy Statistics Exercises Home.
Next: Write a NumPy program to get the minimum and maximum value of a given array along the second axis.

Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.