Here's my solution. *Not exactly the most elegant thing (I don't like the calculate function right now), but it works. *If I get a cuter version, I'll post it as well, but I don't think I'll rework on it though.
Code:
#!/usr/bin/env python
from __future__ import division
import sys
import string
# This function takes every argument the user gave and: removes illegal
# characters
#
def correct(l):
operators = ['+', '-', '/', '*']
i = 0
while i < len(l):
if l[i].isdigit():
i += 1
elif l[i] in operators:
i += 1
else:
l.remove(l[i])
return l
# This functions makes sure that the last characyer is an operator, that the
# first 2 characters are numbers and that there is one more number than
# operators.
#
def check(l):
operators = ['+', '-', '/', '*']
if not l[-1] in operators:
print "Invalid Syntax"
return 1
if not (l[0].isdigit() and l[1].isdigit()):
print "Invalid Syntax"
return 1
n_count, o_count = 0, 0
for i in l:
if i.isdigit():
n_count += 1
else:
o_count += 1
if not (n_count == o_count + 1):
print "Invalid Syntax"
return 1
# This function will calculate the result of the equation and returns it
#
def calculate(l):
operators = ['+', '-', '/', '*']
result = None
# While loop here
#
while l != [result]:
new_l = []
new_l.append(l[0]) # Append first number
pos_op = len(l)
for op in operators:
try:
if l.index(op) < pos_op:
pos_op = l.index(op)
except ValueError:
continue
new_l.append(l[pos_op])
new_l.append(l[1]) # Append second number
del l[pos_op]
del l[0]
del l[0]
try:
result = str(eval("%s %s %s" % (new_l[0], new_l[1], new_l[2])))
except SyntaxError:
print "Invalid syntax"
sys.exit(1)
l.insert(0, result)
return result
if __name__ == '__main__':
while 1:
try:
equation = raw_input('> ')
except KeyboardInterrupt:
break
except EOFError:
break
if equation == "$":
break
eq = equation.split(' ') # Make an list
eq = correct(eq) # Remove unwanted chars
# If eq is empty, ask for input again
#
if eq == []:
continue
incorrect = check(eq)
if incorrect: continue
ans = calculate(eq)
print ans
EDIT: POsted cleaner version
Bookmarks