繁体   English   中英

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可能的listssums < x 这可以通过两个嵌套的for-loopsitertools.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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM