samedi 23 janvier 2021

Is there any to generate an arithmetic operator at random and get it validated?

I try to make a list of arithmetic operations randomly taking the operators into account. In this case I try to add an operator like the parentheses, but I want to make it random in both parts. Example: - (2) + (51) = But when programming this part it throws me something like this:

23) + 45) =

(8) + (77) =

--95 - -94 =

-(-20 + (-83 =

46) + 78) =

-(-9 - (-34 =

--85 - -35 =

-(-83 + (-74 =

This is my code:

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()

How can I randomly and correctly generate the parentheses at both ends of the number?

Thanks very much for readme. Regards.




Aucun commentaire:

Enregistrer un commentaire