0
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

No Uce
  • 23
  • 5
  • why do you sort 10 times? – Patrick Artner Nov 28 '21 at 13:24
  • @PatrickArtner my mistake , but I need to re randint if the list doesn't included 1,2,3,4,5 in their list. Must I use while loop ? or what – No Uce Nov 28 '21 at 13:29
  • Take the range(1, 6) add random numbers from this range, then create a random permutation of the results so the initial constant numbers are in random places and not all at the beginning. Or select a random number between 1...n-4 and take that many 1s, then a random number between 1...n-4-k, where k is sum of items taken so far for each next number, then randomize the order (random permutation). See if you can code this yourself, if not let me know. – Danny Varod Nov 28 '21 at 14:18

2 Answers2

0

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.

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
0

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().

Ali_Sh
  • 2,667
  • 3
  • 43
  • 66