不返回以前返回的所有数字范围内的值的随机数生成器?

2021-10-17 18:20:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我的目标是生成介于(0,500)之间的随机数,但是任何新的数都必须比序列中先前返回的值至少多/少120。我在处理中使用Python,它有一个函数-random(),它接受2个参数并在它们之间返回一个随机数。你知道吗

3条回答
网友
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]

网友
2楼 ·

希望根据您的约束返回一个随机数:

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
网友
3楼 ·

尝试:

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

相关问题