NumPy: Create a random vector of size 10 and sort it
8. Sort Random Vector of Size 10
Write a NumPy program to create a random vector of size 10 and sort it.
Sample Solution:
Python Code :
# Importing the NumPy library as np
import numpy as np
# Generating a 1D array of 10 random numbers between 0 and 1 using np.random.random()
x = np.random.random(10)
# Printing the original array 'x'
print("Original array:")
print(x)
# Sorting the array 'x' in ascending order using x.sort()
x.sort()
# Printing the sorted array 'x'
print("Sorted array:")
print(x)
Sample Output:
Original array: [ 0.73123073 0.67714015 0.95615347 0.4759837 0.88789818 0.69104042 0.59996415 0.26144489 0.51618644 0.89943882] Sorted array: [ 0.26144489 0.4759837 0.51618644 0.59996415 0.67714015 0.69104042 0.73123073 0.88789818 0.89943882 0.95615347]
Explanation:
In the above code –
x = np.random.random(10): This line creates a 1D array x with 10 random numbers between 0 and 1 using the np.random.random() function. The input integer 10 specifies the output array size.
x.sort(): This line sorts the array x in ascending order using the x.sort() method. The array x is modified in-place, meaning that the sorted values are stored back in the original array.
Finally print() function prints the sorted 1D array x.
Pictorial Presentation:
For more Practice: Solve these Related Problems:
- Generate a random vector of size 10 and sort it in ascending order using np.sort.
- Create a function that sorts a vector in descending order by reversing the sorted array.
- Shuffle a vector of size 10, sort it, and then find the median value of the sorted vector.
- Implement a solution that sorts a vector using np.argsort and then reorders the original vector accordingly.
Python-Numpy Code Editor:
Previous: Write a NumPy program to normalize a 3x3 random matrix.Next: Write a NumPy program to find the nearest value from a given value in an 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