How to write a program that fills a 10-position vector with random integers between 0 and 20?

Asked

Viewed 275 times

3

How do I create a vector v of 10 random elements in which each element is one whole between 0 and 20?

I tried to use the function np.random.random((1,10)), but the output was a vector of decimal numbers only

Follow what I’ve done:

#ENTRADA:
import numpy as np
v = np.random.random((1,10))
print(v)

#SAÍDA
[[0.41153214 0.72635035 0.28634792 0.10726119 0.07231721 0.53886811
  0.09092156 0.75656757 0.59052976 0.95628254]]
  • Although the duplicate suggested above does not have exactly the same title, I think it will not be difficult to adapt the answers you have there for your specific case

2 answers

4

To answer this question you can use the following code:

import numpy as np

v = np.random.randint(0, 21, 10)
print(v)

Note that the vector v will be mounted with 10 values belonging to the closed interval [0, 20]

3

You can use np.random.randint to generate the random number, in which case the numbers can repeat.

This returns a list:

v = [np.random.randint(0, 21) for i in range(10)]

type(v)
list

This returns a numpy array:

x = np.random.randint(21, size = 10)

type(x)
numpy.ndarray

Browser other questions tagged

You are not signed in. Login or sign up in order to post.