user12207831
user12207831

Reputation: 55

How to create a random value list with specific length with each value at least once within the range in Python?

I want to create a random value list with specific length with each value at least once within a range using Python. Below is my Python code:

import random

Start = 1
Stop = 5
limit = 6

RandomListOfIntegers = [random.randint(Start, Stop) for iter in range(limit)]
print(RandomListOfIntegers)

I got an output list at one run as below:

[1, 4, 2, 4, 1, 5]

In the above output within start and stop range (1-5) 3 is missing. But I want the list with each value at least once within the range. My expected output as below:

[1, 3, 2, 4, 1, 5]

Guide me to get the above output. Thanks in advance.

Upvotes: 1

Views: 704

Answers (3)

RMPR
RMPR

Reputation: 3511

You can generate all the numbers, shuffle what you generated then add random number to reach the limit:

import random

Start = 1
Stop = 5
limit = 6
RandomListOfIntegers = list(range(Start, Stop+1))
random.shuffle(RandomListOfIntegers)
RandomListOfIntegers.extend(random.choices(RandomListOfIntegers, k=limit-Stop))
print(RandomListOfIntegers)

Upvotes: 2

Gamopo
Gamopo

Reputation: 1598

I think it would be easier to create a list with all the numbers, add extra and then shuffle, like this:

import random

Start=1
Stop=5
Limit=6

mylist = list(range(Start,Stop+1))
for i in range(Limit-(Stop-Start)-1):
    mylist.append(random.randint(Start,Stop))
random.shuffle(mylist)
print(mylist)

it outputs:

[3, 2, 4, 1, 5, 3]

I hope it helps!

Upvotes: 0

azro
azro

Reputation: 54148

You do it in two steps

  • sample the range, with its length, you'll get all the numbers of the interval in random order
  • extend with random number until you reach the limit
randomListOfIntegers = random.sample(range(start, stop + 1), stop) + \
                       [random.randint(start, stop) for iter in range(limit - stop)]

You can also, generate all the values and shuffle them, then add elements to reach the limit

allValues = list(range(start, stop + 1))
random.shuffle(allValues)
randomListOfIntegers = allValues + [random.randint(start, stop) for iter in range(limit - stop)]

Upvotes: 0

Related Questions