[英]how to generate a random matrix less than or equal to another matrix in python
[英]How to use random to print integers whose sum is less than or equal to another integer in Python?
我有一個整數列表,我想打印總和小於或等於變量的所有整數。 我的總和低於 38,如何隨機返回下面列表中我的總和小於或等於 15 的值? 我試圖調整下面的功能,但它不起作用。
j=[4,5,6,7,1,3,7,5]
x = 15
jSum = sum(j)
def decomposition(i):
while i <= x:
n = random.randint(j, i)
yield n
i -= n
print i
decomposition(jSum)
讓我們創建一個list
可能的lists
與sums
< x
這可以通過兩個嵌套的for-loops
和itertools.combinations
來完成:
ops=[list(c) for l in range(1,len(j)) for c in itertools.combinations(j,l) if sum(c) < x]
然后只需使用random.choice
randomly
選擇一個:
random.choice(ops)
當我用j = [4,5,6,7,1,3,7,5]
和x = 15
運行這個時,我得到的隨機輸出是:
[6, 1, 3]
哪個有效! ( sum
< 15
並且所有元素都在j
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.