- Code: Select all
if calc[n] == "*":
return float(calc[n-1])*float(calc[n+1])
etc.
Is there an easier way of doing this? Like how int(calc[n]) would turn the stringy number into a float, is there anything like that for operations?
Thanks
if calc[n] == "*":
return float(calc[n-1])*float(calc[n+1])
def calculate(calc):
while len(calc) > 1:
while "**" in calc:
n = calc.index("**")
calc[n] = float(calc[n-1])**float(calc[n+1])
calc.pop(n+1)
calc.pop(n-1)
while "//" in calc:
n = calc.index("//")
calc[n] = float(calc[n-1])//float(calc[n+1])
calc.pop(n+1)
calc.pop(n-1)
while "/" in calc:
n = calc.index("/")
calc[n] = float(calc[n-1])/float(calc[n+1])
calc.pop(n+1)
calc.pop(n-1)
while "*" in calc:
n = calc.index("*")
calc[n] = float(calc[n-1])*float(calc[n+1])
calc.pop(n+1)
calc.pop(n-1)
while "+" in calc:
n = calc.index("+")
calc[n] = float(calc[n-1])+float(calc[n+1])
calc.pop(n+1)
calc.pop(n-1)
while "-" in calc:
n = calc.index("-")
calc[n] = float(calc[n-1])-float(calc[n+1])
calc.pop(n+1)
calc.pop(n-1)
for n in calc:
return n
>>> import operator
>>> op = {'+': operator.add,
... '-': operator.sub,
... '*': operator.mul,
... '/': operator.div,
... '**': operator.pow,
... }
>>> func = op['*']
>>> func(2, 3)
6
Users browsing this forum: Yahoo [Bot], Yoriz and 8 guests