Leumas - 1 year ago 54
Python Question

# 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 number has to be at a minimum 120 more/less than the previously returned value in the sequence. I am using Python in processing, which has the function -

`random()`
this accepts 2 arguments and returns a random number between them.

Answer Source

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
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download