我的目标是在(0,500)之间生成随机数,但任何新数字必须至少比序列中先前返回的值多120或更少。我在处理中使用Python,它具有函数 - random()
,它接受2个参数并在它们之间返回一个随机数。
答案 0 :(得分:1)
尝试:
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
并使用它:
>>> rand_gen = genrandom()
>>> for i in range(10):
print(next(rand_gen))
411
262
130
320
444
291
32
158
482
6
如果真的无法获得之前任何值的120分之内的值,那么您将很快耗尽您的可能性:
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!")
使用中:
>>> 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
答案 1 :(得分:1)
这应该有希望根据你的约束返回一个随机数:
import random
def randGen(a, b, prev, mindev):
n1 = a if (prev-mindev < a) else (prev-mindev)
n2 = b if (prev-mindev > a) else (prev+mindev)
choiceList = list(set(list(range(500+1))) - set(list(range(n1,n2+1))))
return random.choice(choiceList)
在您的情况下,a = 0,b = 500,mindev = 120。你应该记住上一个。每次调用此函数时都会输入值。
演示运行:
prev = 0
for i in range(10):
prev = randGen(0, 500, prev, 120)
print(prev)
391
159
36
186
15
398
4
296
101
498
答案 2 :(得分:1)
这是一个强力解决方案,但它可能适合您:
from random import randint
def _get_next_number(begin, end, max_diff, prev=None):
if not prev:
return randint(begin, end)
while True:
generated_number = randint(begin, end)
if abs(generated_number - prev) < max_diff:
continue
return generated_number
def generate_numbers(low, high, max_diff, quantity):
previous_generated_number = None
for i in range(quantity):
previous_number = _get_next_number(
low,
high,
max_diff,
previous_generated_number
)
yield previous_number
ten_random_numbers = generate_numbers(0, 500, 120, 10)
print(list(ten_random_numbers))
这应该是这样的:
[341,138,372,153,475,174,418,66,286,125]