Dann geht's auch ein bischen kompakter:gerold hat geschrieben:Ja, diese sind im Modul "operator" versteckt.
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