[英]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.