Python 是否可以在不使用递归的情况下生成排除一组数字的随机数?
问题描述
我查看了 Python Docs(我可能误解了),但我没有看到有在不调用递归函数的情况下执行此操作的方法(如下所示).
我想做的是生成一个随机值,其中不包括中间值.
I looked over Python Docs (I may have misunderstood), but I didn't see that there was a way to do this (look below) without calling a recursive function.
What I'd like to do is generate a random value which excludes values in the middle.
换句话说,
假设我希望 X
是一个不在其中的随机数范围(a - b, a + b)
我可以在第一次通过时这样做吗,
或
1.我是否必须不断生成一个数字,
2. 检查是否在range()
,
3.洗涮涮涮?
In other words,
Let's imagine I wanted X
to be a random number that's not in
range(a - b, a + b)
Can I do this on the first pass,
or
1. Do I have to constantly generate a number,
2. Check if in range()
,
3. Wash rinse ?
至于我为什么不想写递归函数,
1.感觉"我不应该这样做
2. 我这样做的一组数字实际上最终可能会非常大,并且
...我听说堆栈溢出很糟糕,我可能只是在这样做时过于谨慎.
As for why I don't wish to write a recursive function,
1. it 'feels like' I should not have to
2. the set of numbers I'm doing this for could actually end up being quite large, and
... I hear stack overflows are bad, and I might just be being overly cautious in doing this.
我确信有一种很好的、Pythonic、非递归的方式来做这件事.
I'm sure that there's a nice, Pythonic, non-recursive way to do it.
解决方案
使用random.choice().在此示例中,a 是您的下限,b 和 c 之间的范围被跳过,d 是您的上限.
Use random.choice(). In this example, a is your lower bound, the range between b and c is skipped and d is your upper bound.
import random
numbers = range(a,b) + range(c,d)
r = random.choice(numbers)
相关文章