Tech Qu: Implement a post fix evaluator supporting {+,-,*,/}

Post Fix (aka Reverse Polish Notations) is what I used heavily in my student days with a HP-21 Calculator, and later HP-25. I actually have a preference for using it because of it’s superior performance and simplicity of implementation.

Code Snippet
  1. public static double PostFix(IEnumerable<string> terms)
  2. {
  3. double first, second;
  4. var work = new Stack<double>();
  5. foreach (var term in terms)
  6. {
  7. switch (term)
  8. {
  9. case "+":
  10. work.Push(work.Pop() + work.Pop());
  11. break;
  12. case "*":
  13. work.Push(work.Pop() * work.Pop());
  14. break;
  15. case "-":
  16. first = work.Pop();
  17. second = work.Pop();
  18. work.Push(second - first);
  19. break;
  20. case "/":
  21. first = work.Pop();
  22. second = work.Pop();
  23. work.Push(second / first);
  24. break;
  25. default: // no error handling
  26. work.Push(double.Parse(term));
  27. break;
  28. }
  29. }
  30. return work.Pop();
  31. }

Unit tests are easy to write:

Code Snippet
  1. char[] sep = {' ', '\t', '\r', '\n'};
  2. string[] testcases = {"5 1 2 + 4 * + 3 -","10 2 /"};
  3. foreach(var testcase in testcases)
  4. {
  5. var answer = Questions.PostFix(testcase.Split(sep, StringSplitOptions.RemoveEmptyEntries));
  6. Console.WriteLine(string.Format("{0}={1}",testcase,answer));
  7. }

The results are shown below.

For automated testing, just have a second array with the expected answers (or read everything in from XML).

Comments

Popular posts from this blog

Yet once more into the breech (of altered programming logic)

Simple WP7 Mango App for Background Tasks, Toast, and Tiles: Code Explanation

How to convert SVG data to a Png Image file Using InkScape