w3resource

NumPy: Shuffle numbers between 0 and 10

NumPy: Random Exercise-6 with Solution

Write a NumPy program to shuffle numbers between 0 and 10 (inclusive).

Sample Solution:

Python Code :

# Importing the NumPy library as np
import numpy as np

# Generating an array 'x' with numbers from 0 to 9 using np.arange()
x = np.arange(10)

# Shuffling the elements of the array 'x' in-place using np.random.shuffle()
np.random.shuffle(x)

# Printing the shuffled array 'x'
print(x)

# Generating a permutation of numbers from 0 to 9 using np.random.permutation()
# and printing the result
print("Same result using permutation():")
print(np.random.permutation(10))

Sample Output:

[2 7 1 5 3 9 0 4 6 8]                                                  
Same result using permutation():                                       
[8 9 0 4 7 3 1 6 5 2]

Explanation:

In the above code –

x = np.arange(10): This code creates an array x of integers from 0 to 9 using the np.arange() function. The input argument 10 specifies that the array should contain integers from 0 up to, but not including, 10.

np.random.shuffle(x): This code shuffles the elements in the x array in-place (i.e., without creating an array) using the np.random.shuffle() function. The original order of the elements in the array x is randomly assigned.print(np.random.permutation(10)): This code generates an array containing a random permutation of integers from 0 to 9 using the np.random.permutation() function. The input argument 10 specifies that the output array should contain integers from 0 up to, but not including, 10. The function returns an array without modifying the input integer.

Finally, the print() function displays the newly created array.

Pictorial Presentation:

NumPy Random: Shuffle numbers between 0 and 10.

Python-Numpy Code Editor:

Previous: Write a NumPy program to create a random 10x4 array and extract the first five rows of the array and store them into a variable.
Next: Write a NumPy program to normalize a 3x3 random matrix.

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://w3resource.com/python-exercises/numpy/python-numpy-random-exercise-6.php