“切片"一个数变成三个随机数 [英] "Slice" a number into three random numbers
本文介绍了“切片"一个数变成三个随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要生成一个每行(10 行)填充三个随机"值的文件,但这些值的总和必须等于 15.
I need to generate a file filled with three "random" values per line (10 lines), but those values sum must equal 15.
结构为:INDEX A B C".
The structure is: "INDEX A B C".
示例:
1 15 0 0
2 0 15 0
3 0 0 15
4 1 14 0
5 2 13 0
6 3 12 0
7 4 11 0
8 5 10 0
9 6 9 0
10 7 8 0
推荐答案
如果数字可以任意组合使用:
If the numbers can by any just use combinations:
from itertools import combinations
with open("rand.txt","w") as f:
combs = [x for x in combinations(range(16),3) if sum(x ) == 15 ][:10]
for a,b,c in combs:
f.write("{} {} {}\n".format(a,b,c))
这篇关于“切片"一个数变成三个随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文