NumPy: Partition an array in a specified position and move all the smaller elements to the left
7. Partition Array by Specified Position
Write a NumPy program to partition a given array in a specified position and move all the smaller elements values to the left of the partition, and the remaining values to the right, in arbitrary order (based on random choice).
Sample Solution:
Python Code:
# Importing the NumPy library
import numpy as np
# Creating an array of integers
nums = np.array([70, 50, 20, 30, -11, 60, 50, 40])
# Displaying the original array
print("Original array:")
print(nums)
# Partitioning the array at the 4th position
print("\nAfter partitioning on 4 the position:")
print(np.partition(nums, 4))
Sample Output:
Original array: [ 70 50 20 30 -11 60 50 40] After partitioning on 4 the position: [-11 30 20 40 50 50 60 70]
Explanation:
nums = np.array([70, 50, 20, 30, -11, 60, 50, 40]): This line creates a NumPy array nums containing eight integer elements.
print(np.partition(nums, 4)): This line uses the np.partition function to partition the array nums at the specified index position, 4. The result is a new array where the elements before the specified index are smaller or equal to the element at the index position, and the elements after the index are greater or equal to the element at the index position. The order of elements within each partition is not guaranteed to be sorted. In this case, the output might look like [-11 20 30 40 50 50 60 70].
Pictorial Presentation:
For more Practice: Solve these Related Problems:
- Partition a 1D array at a given pivot using np.partition so that elements less than the pivot come before those greater than or equal to it.
- Create a function that accepts an array and a partition index, then returns the array partitioned with the pivot in its sorted position.
- Implement a solution that randomly selects a pivot value and partitions the array accordingly, then validates the ordering.
- Test the partitioning function on arrays with negative, zero, and positive values to ensure robust behavior.
Python-Numpy Code Editor:
Previous: Write a NumPy program to sort a given complex array using the real part first, then the imaginary part.Next: Write a NumPy program to sort the specified number of elements from beginning of a given array .
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