import os.path
from random import randint, choice
from sympy import Symbol, expand
x = Symbol('x')

def preambule(*packages):
	p = ""
	for i in packages:
		p = p+"\\usepackage{"+i+"}\n"
	return p

start = "\\documentclass[12pt,a4paper,french]{article}\n\\usepackage[utf8]{inputenc}\n"
start = start + preambule('amsmath','lmodern','babel')
start = start + "\\begin{document}\n\\begin{align*}\n"

end = "\\end{align*}\n\\end{document}"

# création de la liste d'exercices

body = ""

for n in range(21):
    a = choice([1, -1]) * randint(2, 9)
    b = choice([1, -1]) * randint(2, 9)
    c = choice([1, -1]) * randint(2, 9)
    d = choice([1, -1]) * randint(2, 9)
    e = (a*x+b)*(c*x+d)
    eresultchain = str(expand(e)) # on convertit le résultat en chaîne de caractères
    eresultchain = eresultchain.replace('**','^') # on met au format TeX les exposants
    eresultchain = eresultchain.replace('*','') # on élimine les symboles '*'
    echain = str(e)
    echain = echain.replace('*','')

    body = body+echain+" & = "+eresultchain+"\\\\\n"

# création du fichier .tex

container = start + body + end

file = "monfichier.tex"
if os.path.exists(file):
	os.remove(file)

fichier = open(file , "x") # "x" pour la création et l'écriture
fichier.write(container)
fichier.close()

# compilation LaTeX

instructions = "pdflatex " + file
os.system(instructions)

readpdf = "START " + file[:-4] + ".pdf"
os.system(readpdf)