有没有办法随机生成算术运算符并对其进行验证?
Is there any way to generate an arithmetic operator at random and get it validated?
我尝试随机列出算术运算,同时考虑到运算符。在这种情况下,我尝试添加一个像括号这样的运算符,但我想让它在两个部分都是随机的。示例:- (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} =\n\n')
archivo.write('-----------------------\n')
up=0
for i in range(insert):
up+=1
archivo.write(f'{result[i]}\n\n')
archivo.close()
如何随机正确生成数字两端的括号?
您似乎想要生成 both the left and right parentheses
或 none of them
。
最简单的方法之一是修改:
parenthesis=['', '(']
parenthesis1=['', ')']
# ...
opt=random.choice(parenthesis)
opt1=random.choice(parenthesis1)
进入:
parenthesis=[('',''),('(',')')]
# ...
opt,opt1=random.choice(parenthesis)
我尝试随机列出算术运算,同时考虑到运算符。在这种情况下,我尝试添加一个像括号这样的运算符,但我想让它在两个部分都是随机的。示例:- (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} =\n\n')
archivo.write('-----------------------\n')
up=0
for i in range(insert):
up+=1
archivo.write(f'{result[i]}\n\n')
archivo.close()
如何随机正确生成数字两端的括号?
您似乎想要生成 both the left and right parentheses
或 none of them
。
最简单的方法之一是修改:
parenthesis=['', '(']
parenthesis1=['', ')']
# ...
opt=random.choice(parenthesis)
opt1=random.choice(parenthesis1)
进入:
parenthesis=[('',''),('(',')')]
# ...
opt,opt1=random.choice(parenthesis)