-1

So I have a piece of code:

def test(num):
    count = 1
    l = []
    while len(l) < 16:
        x = num % count
        if x >= 16 or x in l:
            pass
        else:
            l.append(x)
        
        count += 1
    
    return l

that takes a number 45071 for example and modulos it with count, which starts at 1 and goes up by one every loop cycle. Then, if 45071 % count is less than 16, it is appended to a list unless the same value is already there. This loop stops once there are 16 numbers in the list, from 0 to 15. Here is the results of a test run:

>>> print(test(45071))
[0, 1, 2, 3, 5, 7, 8, 4, 11, 15, 14, 13, 12, 6, 9, 10]

This works and all, but with bigger lists and lots of different numbers it gets quite slow. I was wondering if there is any way to make this faster, or another way to get a list of numbers from 0 to 15. The more 'random' the numbers the better. Thanks in advance!

2 Answers2

1

As quite a few people have suggested already, use random. It's not really random (nothing is) -- if you call random.seed with the same seed and make the same pseudo-random function calls afterwards, you'll always get the same pseudo-random results.

>>> import random
>>> def shuffled_ints(n, seed):
...     random.seed(seed)
...     ints = list(range(n))
...     random.shuffle(ints)
...     return ints
...
>>> shuffled_ints(16, 45071)
[0, 10, 12, 14, 8, 1, 15, 2, 13, 7, 6, 5, 3, 9, 11, 4]
>>> shuffled_ints(16, 1234)
[3, 2, 6, 4, 7, 10, 8, 5, 11, 12, 13, 9, 15, 0, 1, 14]
>>> shuffled_ints(16, 45071)
[0, 10, 12, 14, 8, 1, 15, 2, 13, 7, 6, 5, 3, 9, 11, 4]

Using shuffle (or an equivalent) is more efficient than your original method because you don't need to keep generating random numbers and throwing them out.

A slightly more concise version might be to use random.sample:

def shuffled_ints(n, seed):
    random.seed(seed)
    return random.sample(range(n), n)
Samwise
  • 68,105
  • 3
  • 30
  • 44
0

If you're just looking for random numbers then you can use a library with this functionality. For example random.randrange() or numpy.random.rand()

Simon
  • 43
  • 8