NumPy: Partition an array in a specified position and move all the smaller elements to the left
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:
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