Besoin de coder un compilateur de calcul.

Fermé
MEZIANE002 - 25 mai 2022 à 20:04
yg_be Messages postés 22730 Date d'inscription lundi 9 juin 2008 Statut Contributeur Dernière intervention 26 avril 2024 - 26 mai 2022 à 13:15
Bonjour,
je cherche à coder un compilateur de calcul en python.
Il est déjà assez avancé, il possède plusieurs fonctions, je cherche actuellement à utiliser mes informations (listes etc...) pour justement calculer.
voila le code:
import re
wl=[]

#Ordre des opérations
op = {
"+" : 2,
"-" : 1,
"*" : 4,
"/" : 3,
"^" : 5,
"%" : 4,
"=" : 0
}

#Code des opérations (de la forme "operateur" : "code")
do = {
"+" : "out = a+b",
"-" : "out = a-b",
"/" : "out = a/b",
"*" : "out = a*b",
"^" : "out = a**b",
"%" : "out = a%b",
"=" : "if a == b:\n out = 1\nelse:\n out = 0"

}

#Créer le regex de split des opérations
txt = ""
for i in op:
txt+="\\" + i + "|"
txt = txt[:len(txt)-1]
print(txt)

#Fonction de collage d'instruction
def init(x):
c=""
for i in range(len(x)):
if x[i] != " ":
c+=x[i]
return c

#transforme les "--" en "+"
def simplify(x):
c = list(x)
for i in range(len(c)):
if c[i] == "-" and c[i+1] == "-":
c[i] = "+"
c[i+1] = ""
return ''.join(c)

#Tri des opérations
def cle(v):
return -op[v[0]]
def ordre(l):
r=sorted(l,key=cle)
return r

#Récupère les opérateurs et leur positions
def get_operators(x):
global op
global wt
l = []
d = [0]
for i in range(len(x)):
if x[i] in op and i!=0:
d.append(i-1)
l.append([x[i],i+1])
d.append(len(x)-1)
wt=l
return ordre(l)

def delimit(x):
global op
d = [0]
for i in range(len(x)):
if x[i] in op and i!=0:
d.append(i+1)
d.append(len(x)-1)
d.pop(len(d)-1)
return d

"""Transforme un calcul sous forme de liste de deux éléments comme : simple(["-1", "7"], "+") en son résultat (ici 6)"""
def simple(nm, opr):
global op
global do

num = nm
ope = opr

doc = {
"out" : 0,
"a" : float(num[0][0]),
"b" : float(num[1][0])
}
if ope in do:
exec(do[ope], doc)
return doc["out"]
def recompose(l, l2):
c=str(l[0][0])
for i in range(len(l2)):
c+=l2[i][0]
c+=l[i+1][0]
return c

#Fonction d'analyse de string
def analyse(x):
pos = {}
global txt
global wt
c = simplify(init(x))
l = get_operators(c)
num = re.split(txt, c)
lim = delimit(c)
if num[0] == "":
num.pop(0)
num[0] = c[0]+num[0]
for i in range(len(num)):
num[i] = [num[i], lim[i]]
#Le code ici



print("le calcul: "+c)
print("les opérations triés: "+str(l))
print("les nombres et leur position: "+str(num))
print("les opérations non-triés: "+str(wt))
print("les délimitétions des nombres: "+str(delimit(c)))

analyse("-1*4^4-7")
print(simple(["2", "4"], "+"))

Merci ^^
A voir également:

2 réponses

yg_be Messages postés 22730 Date d'inscription lundi 9 juin 2008 Statut Contributeur Dernière intervention 26 avril 2024 1 477
26 mai 2022 à 12:55
bonjour,
peux-tu spécifier le langage quand tu utilises les balises de code, comme expliqué ici?

as-tu une question à propos de ton code?
0
yg_be Messages postés 22730 Date d'inscription lundi 9 juin 2008 Statut Contributeur Dernière intervention 26 avril 2024 1 477
Modifié le 26 mai 2022 à 13:18
Ton utilisation de exec() et de ton dico do est un peu particulière.
Moi je suggère plutôt de mettre des fonctions dans le dico do, ainsi:
def opsum(a,b):
    return a+b
do = {
    "+" : opsum,
    "-" : lambda a, b: a-b,
    "/" : lambda a, b: a-b,
    "*" : lambda a, b: a*b,
    "^" : lambda a, b: a**b,
    "%" : lambda a, b: a%b,
    "=" : lambda a, b:  a == b
}
def calc(ope,a,b):
    if ope in do:
        return do[ope](a,b)
print(calc("+",5,8))

Pour l'opération "+", j'ai mis une fonction classique, tandis que j'ai mis des fonctions lambda pour les autres opérations. Comme cela tu as un exemple des deux méthodes.
0