Skip to content
Advertisement

How do I get random numbers that fully cover a range?

I’m trying to have random integers between (1,5) but the catch is displaying all of the values from the random integer in a for loop ranging of 10 loops. I only have access to randint() and random() methods in ‘random class’.

from random import randint

eventList = []
taskList = []
dayList = []

def getEventList():
    eventList.sort()
    return eventList

def getTaskList():
    return taskList

def getDayList():
    return dayList

def generateData():
    while len(getTaskList()) < 10:
        # Need to implement a way to stretch the random int while having all the integers present
        randomEvent = randint(1, 5)
        randomTask = randint(10, 30)
        randomDay = randint(1, 9)

        eventList.append(randomEvent)
        dayList.append(randomDay)

        if randomTask not in getTaskList():
            taskList.append(randomTask)

Advertisement

Answer

Based on clarifications in my other answer, I think you meant to ask “how to I get random numbers that fully cover a range?”

You are using randint, and just calling it extra times hoping to get all the values. But depending on random chance, that can take a while.

It would be better to just take all the values you want, e.g. list(range(1,6))
and then just rearrange that with random.shuffle
https://docs.python.org/3/library/random.html#random.shuffle

import random
values = list(range(1, 6))
random.shuffle(values)
print(values)

Obviously, if this is what you want to do, but your prof says you can’t use that function, then you should use that function, get working code, and only THEN write your own replacement for the standard library. (so you only have to debug one or the other)

So write your own version of shuffle. I’ll leave the details to you, but it should be pretty easy to use randint to pick one of the available entries, removing it, and so on.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement