User Tools

Site Tools


Writing /var/www/html/conf/plugins.local.php failed
codeapalooza:challenge_4

Table of Contents

Problem

`Implement a mathematical expression evaluator`

Basically take a string such as:

"(45 - 5) / 10"

and find the result. The engine must support basic substitution as well, example:

"(width / 2) - offset"

Here are the rules:

  • you CAN NOT use python's eval() function
  • you CAN NOT use language XYZ's eval() function
  • support basic arithmetic operators +,-,*,/
  • support bracketed expressions
  • integer values (bonus: support decimal values)
  • positive integer values (bonus: support negative values)
  • evaluate from left to right (bonus: support proper order of operations)

Feel free to use whatever syntax you like for the variables ('variable', ${variable}, :variable, etc).

Examples

An example implementation might look like this:

# prints 6
print evaluate("10 - 6 + 2")
# prints 2
print evaluate("(10 - 6) / 2")
# prints 4
print evaluate("poo - 12 / 3", {poo: 24})

Solutions

Josh using Java

To run this, use the following command line:

java -jar eval.jar "2 + 2"

or to pass a set of variables, use ECMA style syntax

java -jar eval.jar "poo + pee" "{poo: 2, pee: 4}"

Gabriel Using Python

Examples:

      python calc.py "2 + 2"
      python calc.py "2 + 3.5*(1 - 7e-3)"

With variable substitution:

      python calc.py "$poo + $pee" poo:2 pee:4

Jason Using Python

There are two files: the original, eval.py and the Gabriel modified eval2.py. eval2.py allows for spaces in equations and variable names that can be found within other variable names.

Examples:

      python eval.py 2 + 2
      python eval.py 2+3.5*(1-7e-3)

With variable substitution:

      python eval2.py "$poo + $pee" poo:2 pee:4
codeapalooza/challenge_4.txt · Last modified: 2010/05/27 14:04 (external edit)