[英]Randomly generating 3-tuples with distinct elements in python
I am trying to generate 3-tuples (x,y,z)
in python such that no two of x
, y
or z
have the same value. 我试图在python中生成3元组
(x,y,z)
以使x
, y
或z
中没有两个具有相同的值。 Furthermore , the variables x
, y
and z
can be defined over separate ranges (0,p)
, (0,q)
and (0,r)
. 此外,变量
x
, y
和z
可以在单独的范围(0,p)
, (0,q)
和(0,r)
。 I would like to be able to generate n
such tuples. 我希望能够生成
n
这样的元组。 One obvious way is to call random.random()
for each variable and check every time whether x=y=z
. 一种明显的方法是为每个变量调用
random.random()
并每次检查x=y=z
。 Is there a more efficient way to do this ? 有更有效的方法吗?
You can write a generator that yields desired elements, for example: 您可以编写一个生成所需元素的生成器,例如:
def product_no_repeats(*args):
for p in itertools.product(*args):
if len(set(p)) == len(p):
yield p
and apply reservoir sampling to it: 并对其进行油藏采样 :
def reservoir(it, k):
ls = [next(it) for _ in range(k)]
for i, x in enumerate(it, k + 1):
j = random.randint(0, i)
if j < k:
ls[j] = x
return ls
xs = range(0, 3)
ys = range(0, 4)
zs = range(0, 5)
size = 4
print reservoir(product_no_repeats(xs, ys, zs), size)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.