jeudi 4 février 2021

How to create a random list with mathematical operators in an aesthetic way without it being redundant?

This month I have been working with the random module and I want to learn everything that is necessary until I have mastered it correctly. So I am trying to make a list where random values are printed with mathematical operators including parentheses, but the problem comes when I do the evaluation and it is printed redundantly. I try to do this:

1.- (2)(3)
2.- (-4)12
4.- -2(3)
5.- 2*3
6.- 18·12
7.- 1×2

And prevent this from happening:

1.- (2)*(3)
2.- (-4)*12
4.- -2×(3)
5.- (2)-3

Mi código:

from random import randint,choice

archivo=open('EjsPapu.txt', 'w')
insert=int(input('Valor: '))
fmts = (
    '({})*({})',
    '-({})*({})',
    '({})*(-{})',
    '-({})*(-{})',
    '(-{})*(-{})',
    '-(-{})*(-{})',
    '({})*({})',
    '-({})*({})',
    '({})*(-{})',
    '-({})*(-{})',
    '(-{})*(-{})',
    '-(-{})*(-{})',
 )

result=[]
for i in range(insert):
    x,y = randint(1,99), randint(1,99)
    expr = choice(fmts).format(x,y)
    print(f"{expr} = {eval(expr)}")
    result.append(eval(expr))
    archivo.write(f'{expr}\n\n')

archivo.write('------------------------------\n\n')
for i in range(insert):
    archivo.write(f'{result[i]}\n\n')
archivo.close()

    

By the way, if there is any way to optimize the code meeting the criteria I want it to do, I would greatly appreciate it. Greetings.




Aucun commentaire:

Enregistrer un commentaire