是否有任何方法可以随机生成算术运算符并进行验证?



考虑到运算符,我尝试随机列出一个算术运算列表。在这种情况下,我尝试添加一个像括号一样的操作符,但我想使它在两个部分都是随机的。例如:- (2) + (51) =但是当编程这部分时,它会给我这样的提示:

23) + 45) =
(8) + (77) =
--95 - -94 =
-(-20 + (-83 =
46) + 78) =
-(-9 - (-34 =
--85 - -35 =
-(-83 + (-74 =

这是我的代码:

import random
archivo=open('Ejercicio1.7.txt', 'w')
options_operators=['+', '-']
options_operators1=['-', '']
parenthesis=['', '(']
parenthesis1=['', ')']
up=0
result=[]
insert=int(input('Valor: '))
for i in range(insert):
up+=1
num1=random.randint(1, 100)
num2=random.randint(1, 100)
options=random.choice(options_operators)
options1=random.choice(options_operators1)
opt=random.choice(parenthesis)
opt1=random.choice(parenthesis1)
result.append(eval(str(options1)+str(opt)+str(num1)+str(opt1)+str(options)+str(opt)+str(num2)+str(opt1)))
archivo.write(f'{options1}{num1} {options} {num2} =nn')
archivo.write('-----------------------n')
up=0
for i in range(insert):
up+=1
archivo.write(f'{result[i]}nn')
archivo.close()

如何在数字的两端随机正确地生成括号?

似乎您想生成both the left and right parenthesesnone of them

最简单的方法之一是修改:

parenthesis=['', '(']
parenthesis1=['', ')']
# ...
opt=random.choice(parenthesis)
opt1=random.choice(parenthesis1)

为:

parenthesis=[('',''),('(',')')]
# ...
opt,opt1=random.choice(parenthesis)

相关内容

最新更新