【发布时间】:2020-01-14 09:18:09
【问题描述】:
import operator
import random
# these modules will help with the random picking of operators
ops = {"+": operator.add, "-": operator.sub}
a = ["+", "-"] #this is to do the random.choice() function
b = float(ops[random.choice(a)](0, 1)) #these can only take 2 parameters, don't ask me why
c = float(ops[random.choice(a)](2, 3))
d = float(ops[random.choice(a)](4, 5))
e = float(ops[random.choice(a)](6, 7))
f = float(ops[random.choice(a)](8, 9))
print(b+c+d+e+f) #I have no idea how to do random operators here so i just added
while b+c+d+e+f != 5: #to over and over until i get 5
if b+c+d+e+f == 5: #if that finally happens...
print(b+c+d+e+f) #print 5
所以想法是使用数字 0-9 之间的随机运算符得到 5。
我真的不知道要使用什么代码。 operator.add() 函数只接受 2 个参数。
如果有人可以告诉我如何输入更多参数,那真的很有帮助。
简单来说,数字 0,1,2,3,4,5,6,7,8,9 需要在每个数字之间加上 + 或减号,才能得到数字 5。
【问题讨论】:
-
那么你需要5个随机数和4个随机运算符吗?
-
仅供参考,
ops = [add, sub]; random.choice(ops)会做得很好,而不是你这样做的双重间接方式......