'i want to fill an array which his length is 20 with randomly number from 1 to 100 in python
i want to fill an array which his length is 20 with randomly number from 1 to 100 in python
import numpy as np
a = np.empty(shape=5)
print(a)
for i in range(50){
a[i]=randint(1,100);}
Solution 1:[1]
You can both create an array or fill an array with 20 random integers using numpy.random.randint():
import numpy as np
# create an 20-element array of random integres in [1, 100]
a = np.random.randint(1, 101, size = 20)
print(a)
# create an uninitialized array of 20 integers
b = np.empty(20, dtype = int)
# fill b with 20 random integers in [1, 100]
for i in range(len(b)):
b[i] = np.random.randint(1, 101, size = 1)
print(b)
Sample Output:
# array a
[56 39 20 14 78 58 86 72 67 87 79 78 84 49 43 80 79 21 46 31]
# array b
[50 26 87 22 6 37 36 32 84 79 62 2 79 45 90 66 67 30 26 85]
In my code above:
numpy.random.randint(1, 101, size = 20)(documentation) creates a 20-element array of random integers in the closed interval[1, 100];numpy.random.randint(1, 101, size = 1)creates a scalar array (1-element) of a random integer in the closed interval[1, 100]. We generate 20 such random integers and assign each of them to a different element of the arraybof integers.
Notes regarding your code:
a = np.empty(shape=5)(documentation) creates an uninitialized array of5floats; if you need20elements, this should be20;- if you need an array of integers, you should specify this using the
dtypeoptional argument as I have done above. If you do not specifydtype, by default, you will be allocated an uninitialized array of floats.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
