Leumas Leumas - 18 days ago 5
Python Question

python: Random number generator that doesn't return values in range of all previously returned numbers

My goal is to generate random numbers between (0,500), but any new numbers have to be at minimum 120 more/less than any previously returned values. I am using python in processing, it has the function - random(), which accepts 2 arguments and returns a random number between them.

Answer

Try:

import random

def  genrandom():
    low_lim = 0
    high_lim = 0
    last = 0
    while True:
        low_lim = max(0, last - 120)
        high_lim = min(501, last + 120)
        rand_range = list(range(0, low_lim+1)) + list(range(high_lim,501))
        last = random.choice(rand_range)
        yield last

And use it like:

>>> rand_gen = genrandom()
>>> for i in range(10):
    print(next(rand_gen))

411
262
130
320
444
291
32
158
482
6

Edit:

And if you really can't get a value within 120 of any previous value, you'll exhaust your possibilities pretty quick:

def genrandom2():
    choices = list(range(0, 501))
    while choices:
        choice = random.choice(choices)
        yield choice
        low = max(0, choice - 120)
        high = min(501, choice + 120)
        for i in range(low, high):
            try:
                choices.remove(i)
            except ValueError:
                pass
    print("All done!")

In use:

>>> while True:
    print(next(rand_gen2))

455
168
296
9
All done!
Traceback (most recent call last):
  File "<pyshell#43>", line 2, in <module>
    print(next(rand_gen2))
StopIteration