Skip to content

Instantly share code, notes, and snippets.

@ylyhlh
Last active August 29, 2015 14:02
Show Gist options
  • Save ylyhlh/038c3a0230d95c893eed to your computer and use it in GitHub Desktop.
Save ylyhlh/038c3a0230d95c893eed to your computer and use it in GitHub Desktop.
Python Learning
###################################################
#Here are some codes I wrote in python for learning
###################################################
# A prefix Calculator
import prefixCalclulator
prefixCalclulator.test()
import sys
import unittest
# main calculate function, input is line of prefix expresssion
def calculate(line):
# the set of operators supported
operator_set = set(['+', '/', '*'])
# a function to apply the operators
operator_func = {
'*': lambda pair: pair[0] * pair[1],
'+': lambda pair: pair[0] + pair[1],
'/': lambda pair: pair[0] / pair[1]}
def apply_operator(operator, operand_1, operand_2):
return operator_func[operator]((operand_1, operand_2))
# begin the computing
chars = line.split()
operand_stack = []
while len(chars) != 0:
op = chars.pop()
if op in operator_set:
res = None
try:
res = apply_operator(op, operand_stack.pop(), operand_stack.pop())
except Exception as e:
raise Exception("Error in applying the operater '%s', because %s." % (op, e.args))
#put back the result
operand_stack.append(res)
else:
try:
operand_stack.append(float(op))#prepare for division
except Exception as e:
raise Exception("Error in reading operand(operator) '%s', because %s . " % (op,str(e.args)) )
return int(operand_stack[0])
###################################
# read file and calculate each line
###################################
if __name__ == "__main__":
# check the cmd paras
if len(sys.argv) > 1:
file_name = sys.argv[1]
else:
raise Exception("No filename given!")
# calculate the file
try:
with open(file_name, 'r') as f:
for line in f:
try:
print(calculate(line))
except Exception as e:
print(str(e) + " Fail to calculate line: '%s'." % line.strip())
except IOError:
raise Exception("Reading file '%s' failed!" % file_name)
########################
# Unit Test for function
########################
class PrefixCalculatorTest(unittest.TestCase):
def test_easy(self):
self.assertEqual(calculate("* + 2 3 4"), 20)
def test_onlyOperand(self):
self.assertEqual(calculate("1"), 1)
def test_devide(self):
self.assertEqual(calculate("/ + 10 10 2"), 10)
def test_devideFloat(self):
self.assertEqual(calculate("* / 3 2 2"), 3)
def test():
suite = unittest.TestLoader().loadTestsFromTestCase(PrefixCalculatorTest)
unittest.TextTestRunner(verbosity=2).run(suite)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment