如何创建三个总和为特定值的随机整数? (Python) [英] How can I create three random integers which sum to a specific value? (Python)

查看:225
本文介绍了如何创建三个总和为特定值的随机整数? (Python)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说bob = 6

Let's say bob = 6

我想创建3个随机整数,总和为106(100 + bob的原始整数.它可以是10,但在这种情况下是6).

I want to create 3 random integers that have a sum of 106 (100 + whatever bob's original integer is. It could be 10, but in this case, it's 6).

我有:

from random import *
bob = 6
bob1 = (randint(0,100))
bob2 = (randint(0,100))
bob3 = (randint(0,100))
print bob1
print bob2
print bob3

我可以生成整数,但是如何确定它们的总和= 100 +原始整数? (共106个).如果总和不等于106,那么我希望脚本继续执行,直到达到106.

I can generate integers, but how can I make sure the sum of them = 100 + original integer? (106 total). If the sum doesn't = 106, then I want the script to keep going until it makes 106.

推荐答案

只需计算第三个值:

from random import randint
bob = 6
bob1 = randint(0, 100)
bob2 = randint(0, min(100, 100 + bob - bob1))
bob3 = 100 + bob - bob1 - bob2
print bob1
print bob2
print bob3

这篇关于如何创建三个总和为特定值的随机整数? (Python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆