w3resource

NumPy: Create a random vector of size 10 and sort it

NumPy: Random Exercise-8 with Solution

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:

NumPy Random: Create a random vector of size 10 and sort it.

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.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/numpy/python-numpy-random-exercise-8.php