【问题标题】:Random picking of operators (add,sub) with conditions随机选择有条件的操作符(add,sub)
【发布时间】: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) 会做得很好,而不是你这样做的双重间接方式......

标签: python math pycharm logic


【解决方案1】:

这可能不是最有效或最优雅的方法,但它可以解决问题。总是把你的while循环放在需要做的事情上。在您的示例中,只有 b+c+d+e+f 只是一遍又一遍地计算,而 b、c、d、e 和 f 的运算符和值不会改变。

import random

result = 0
result_str = ""
while result != 5:
    result = 0
    result_str = ""
    for i in range(0,10):
#         here is random decision between operators
        if bool(random.getrandbits(1)):
            result += i
            result_str = result_str + "+" + str(i)
        else:
            result -= i
            result_str = result_str + "-" + str(i)
print(result_str)

【讨论】:

  • 还有一件事,我意识到它只给出了等式,有没有办法确保它也给出答案?不过这不是什么大问题。
  • 就像它也给出'5'?只需底部的print(result) 即可。另外,如果答案是正确的,你能投票吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-16
  • 2021-07-03
  • 1970-01-01
  • 2020-12-01
  • 1970-01-01
  • 2013-11-18
相关资源
最近更新 更多