3

我想要做的是随机生成两个等于给定数字的数字。然而,为了让它得到想要的答案,我希望它是随机的。那就是问题所在。

a=(1,2,3,4,5,6,7,8,9,)
from random import choice
b=choice(a)
c=choice(b)
d= c+b
if d == 10:
#then run the rest of the program with the value's c and b in it
#probably something like sys.exit goes here but I am not sure to end \/
else:
# i have tryied a few things here but I am not sure what will loop it around*

(感谢您的帮助:D)

我知道创建了一个名为“正确”的列表,并且知道尝试将值 a 和 b 附加到列表中,但这是行不通的。因为我知道运行程序'in for trail in range(100)',所以我得到了答案。然而,这些值并没有附加到新的列表中。这是问题所在。然后我要做的是读取列表中的值 0 和 1,然后使用它们。(对不起,它在学校做得不是很好) 这是针对不添加到给定变量的分数。这一点倒是。

import sys
right=(0)
y=x+x
from trail in range(y)
a=(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20)
from random import choice 
A=choice(a)
B=choice(a)
d=A/B
if d==1:
    right.append(A)
    right.append(B)
else:
    x.append(1)
4

3 回答 3

3
 from random import choice

 a = range(1, 10)
 b = c = 0
 while b + c != 10:
     b = choice(a)
     c = choice(a)  # You meant choice(a) here, right?

但这完成了同样的事情:

 b = choice(a)
 c = 10 - b

对于 0 到 10 之间的十进制数:

from random import uniform

b = uniform(0, 10)
c = 10 - b
于 2012-06-19T20:27:06.937 回答
1

也许我错过了重点,但不需要循环来选择两个相加的随机数。一个随机数和简单的减法就可以完成这项工作:

from random import randint

def random_sum(given_number):
    a = randint(1, given_number)
    return a, given_number - a
于 2012-06-19T20:29:06.473 回答
0

这符合的描述,但其他两个答案可能符合您的要求,因为对于任何给定的数字 d,将只有一个其他数字 d',st d+d'=10。所以我的方式是不必要的慢。

goal = 10 #the number you're trying to add up to
sum = 0 
min = 1
max = 9
b = c = 0 # initialize outside your loop so you can access them afterward
while (sum != goal) 
    b = random.randint(min, max) 
    c = random.randint(min, max)
    sum = b+c

但是要回答您实际提出的问题,在 python 中,“继续”将跳出条件块或循环的一次迭代,而“中断”将完全退出循环。sys.exit() 将退出 python,所以这不是你想要的。

于 2012-06-19T20:38:58.093 回答