class operatore: def __init__(self, op, sx, dx): self.op = op self.sx = sx self.dx = dx def valore(self, livello=0): print('| '*livello, 'entering numero.valore', self.op) valsx = self.sx.valore(livello+1) valdx = self.dx.valore(livello+1) if self.op == '*': res = valsx * valdx elif self.op == '+': res = valsx + valdx elif self.op == '-': res = valsx - valdx elif self.op == '/': res = valsx / valdx elif self.op == '%': res = valsx % valdx elif self.op == '**': res = valsx ** valdx else: res = None print("Operatore non conosciuto: " + self.op) print('| '*livello, 'exiting numero.valore', res) return res def semplifica(self, livello=0): print('| '*livello, 'entering operatore.semplifica', self.op) sx = self.sx.semplifica(livello+1) dx = self.dx.semplifica(livello+1) # x + 0 = x if self.op == '+' and sx.isnumber(0): ris = dx elif self.op == '+' and dx.isnumber(0): ris = sx # x * 1 = x elif self.op == '*' and sx.isnumber(1): ris = dx elif self.op == '*' and dx.isnumber(1): ris = sx # x / 1 = x elif self.op == '/' and dx.isnumber(1): ris = sx # x ** 1 = x elif self.op == '**' and dx.isnumber(1): ris = sx # x ** 0 = 1 elif self.op == '**' and dx.isnumber(0): ris = numero(1) print('| '*livello, 'exiting operatore.semplifica', ris) return ris def isnumber(self, N): return False def __str__(self): return "({}{}{})".format( self.sx.__str__(), self.op, self.dx.__str__() ) class numero(operatore): def __init__(self, num): self.num = num def isnumber(self, N): return N == self.num def valore(self, livello=0): print('| '*livello, 'entering numero.valore') res = self.num print('| '*livello, 'exiting numero.valore', res) return res def semplifica(self, livello=0): print('| '*livello, 'entering/exiting numero.semplifica', self.num) return self def __str__(self): return str(self.num) if __name__ == '__main__': zero = numero(0) uno = numero(1) cinque = numero(5) sette = numero(7) piu = operatore('+', cinque, zero) per = operatore('*', piu, uno) due = numero(2) piu2 = operatore('+', zero, uno) espressione = operatore('**', per, piu2) print(espressione) print(espressione.valore()) print(espressione.semplifica())