[英]Randomly generating 3-tuples with distinct elements in python
我試圖在python中生成3元組(x,y,z)
以使x
, y
或z
中沒有兩個具有相同的值。 此外,變量x
, y
和z
可以在單獨的范圍(0,p)
, (0,q)
和(0,r)
。 我希望能夠生成n
這樣的元組。 一種明顯的方法是為每個變量調用random.random()
並每次檢查x=y=z
。 有更有效的方法嗎?
您可以編寫一個生成所需元素的生成器,例如:
def product_no_repeats(*args):
for p in itertools.product(*args):
if len(set(p)) == len(p):
yield p
並對其進行油藏采樣 :
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.