Seite 1 von 1

Verfasst: Mittwoch 26. Oktober 2005, 15:03
von jens
gerold hat geschrieben:Ja, diese sind im Modul "operator" versteckt.
Dann geht's auch ein bischen kompakter:

Code: Alles auswählen

import operator

l = [100, "-", 20, "+", 250.6, "*", 2, "/", 4]

class calc:
    def __init__(self):
        self.ops = {
            "-" : operator.sub,
            "+" : operator.add,
            "*" : operator.mul,
            "/" : operator.div
        }
        self.result = None
        self.last_opt_string = ""
        self.operation = None

    def feed(self, x):
        if self.result == None:
            print x
            self.result = float(x)
            return

        if self.operation != None:
            print self.last_opt_string, x,
            self.result = self.operation(self.result, x)
            print "=", self.result
            self.operation = None
            return

        try:
            self.operation = self.ops[x]
        except KeyError, e:
            print "Unknown Operation:", e
            sys.exit()
        else:
            self.last_opt_string = x

c = calc()
for x in l:
    c.feed(x)

print "="*30
print "Result:", c.result

Verfasst: Mittwoch 26. Oktober 2005, 22:35
von BlackJack
Alles sehr schön, aber was ist eigentlich mit "Punkt vor Strichrechnung"? Das gibt Punktabzug. :twisted:

Verfasst: Donnerstag 27. Oktober 2005, 15:42
von Leonidas
BlackJack hat geschrieben:Alles sehr schön, aber was ist eigentlich mit "Punkt vor Strichrechnung"? Das gibt Punktabzug. :twisted:
Deswegen ahbe ich mir mal einen UPN-Rechner gebaut.. (nein, nicht mit VB!) 8)