jeudi 12 mars 2020

How to generate a randomized list of a sequence of numbers? Python 3

I want a function to generate a list of length n containing an arithmetic sequence of numbers between 0 and 1, but put in a random order.

For example, for the function

def randSequence(n):
    ...
    return myList
randSequence(10)

returns

[0.5, 0.3, 0.9, 0.8, 0.6, 0.2, 0.4, 0.0, 0.1, 0.7]

and

randSequence(5)

returns

[0.4, 0.0, 0.2, 0.8, 0.6]

Currently, I have it so it generates the sequence of numbers in one loop, and randomizes it in another, as follows:

def randSequence(n):
    step = 1 / n
    setList = []
    myList = []
    for i in range(n):
        setList.append(i * step)
    for i in range(n):
        index = random.randint(0, len(setList) - 1)
        myList.append(setList.pop(index))
    return myList

Unfortunately, this solution is slow, especially for large numbers (like n > 1,000,000). Is there a better way to write this code, or even better, is there a function that can do this task for me?




Aucun commentaire:

Enregistrer un commentaire