I recently got help to randomly generate the parentheses without them crossing each other and generating an error. Now I try to make an operator without crossing each other. What I want to do is randomly generate an addition or subtraction with a parenthesis, but without the probability causing them to intersect in that randomness. Example.
I want to avoid this:
(4) + -3
--5 - (28)
And do this:
(4) + (-3)
-(-5) - (28)
My code:
import random
archivo=open('numerosconparentesis.txt', 'w')
options_operators=[('+', '-'),('-','')]
options_general=[('-',''),('','-'),('-','-'),('','')]
parenthesis_operators=[('(',')','',''),('','','(',')'),('','','',''),('(',')','(',')')]
up=0
result=[]
insert=int(input('Ingresa la cantidad de números a generar: '))
for i in range(insert):
up+=1
n1=random.randint(1, 100)
n2=random.randint(1, 100)
options,options1=random.choice(options_operators)
ops,ops1=random.choice(options_general)
opt1,opt2,opt3,opt4=random.choice(parenthesis_operators)
result.append(eval(str(ops)+str(opt1)+str(ops1)+str(n1)+str(opt2)+str(options)+str(opt3)+str(ops)+str(n2)+str(opt4)))
archivo.write(f'{up}.- {ops}{opt1}{ops1}{n1}{opt2} {options} {opt3}{options1}{n2}{opt4} =\n\n')
archivo.write('---------------------\n')
up=0
for i in range(insert):
up+=1
archivo.write(f'{result[i]}\n\n')
archivo.close()
Aucun commentaire:
Enregistrer un commentaire