Home > Blockchain >  how to random 10 numbers between 1 and 5 in list and the list must inculde all number
how to random 10 numbers between 1 and 5 in list and the list must inculde all number

Time:11-28

from random import randint
k=[]
for i in range(10):
    k.append(randint(1,5))
    k.sort()
print(k)

The output will be correct but sometimes it not include value from 1 to 5. for example, maybe k=[2,3,3,3,3,4,4,5,5,5] and not included 1. I need to include all numbers

CodePudding user response:

10 random numbers between 1 and 5 means a list of [1,1,1,1,1,1,1,1,1,1] is a valid result - it is just very unlikely.

If you need to ensure 1 to 5 are in it, start with [1,2,3,4,5] and add 5 random numbers:

from random import choices

k = [1,2,3,4,5]
k.extend( choices(range(1,6), k=5)) # add 5 more random numbers
k.sort()

print(k)

to get

[1,1,2,2,3,4,4,5,5,5]  # etc.

The part choices(range(1,6), k=5) returns a list of 5 numbers in the range 1-5 without need for a loop.

CodePudding user response:

Using NumPy library could have priority over pythonic random to work with to do so; which may be very faster in huge data volumes:

import numpy as np

nums = np.arange(1, 6)                        # create integer numbers from 1 to (6 - 1) to ensure 1 to 5 will be contained
ran = np.random.random_integers(1, 6, 5)      # create 5 random integers from 1 to (6 - 1)
combine = np.concatenate((nums, ran))         # combining aforementioned two arrays together
np.random.shuffle(combine)                    # shuffling the created combined array

which will get arrays like [4 5 4 2 5 1 3 4 2 1], which will contain all integers from 1 to 5. This array can be converted to list by combine.tolist().

  • Related