Skip to content

MarioIannotta/Postfix-expression-evaluator

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

8 Commits
 
 
 
 
 
 

Repository files navigation

Postfix expression evaluator

Evaluate postfix expression with Python.

What is a postfix expression?

From wikipedia: "A postfix expression AKA reverse polish expression is a mathematical notation in which every operator follows all of its operands, in contrast to Polish notation (PN), which puts the operator before its operands." You can read more about it here here.

Basically, instead of write (3 + 4) * 5 you write 3 4 + 5 *.

Why

An expression written in postfix notation is easier to evaluate than a standard one because you don't have to consider parenthesis.

How does the script works?

For a given string rappresenting a postfix expression, the script will calculate

  • the validity (if the expression is properly formatted)
  • the raw tree
  • the formatted tree
  • the expression result
  • the tree depth
  • a visual rappresentation of the expression

Example

Run the script with

python ./postfix.py "your expression here"

Here's an example

python ./postfix.py "1 ln 2 + 3 * 4 sqrt 5 + cos - 6 4 * ln sqrt 4 + +"

Evaluating >> 1 ln 2 + 3 * 4 sqrt 5 + cos - 6 4 * ln sqrt 4 + +

Is valid

raw tree:
`['+', ['+', ['4', [], []], ['sqrt', ['ln', ['*', ['4', [], []], ['6', [], []]], []], []]], ['-', ['cos', ['+', ['5', [], []], ['sqrt', ['4', [], []], []]], []], ['*', ['3', [], []], ['+', ['2', [], []], ['ln', ['1', [], []], []]]]]]`

formatted tree:
((((ln(1)+2)*3)-cos((sqrt(4)+5)))+(sqrt(ln((6*4)))+4))

result:
11.0288074333

depth:
6

tree structure             
                                +

               -                               +

       *             cos            sqrt               4

   +       3               +              ln

ln   2                sqrt   5               *

  1                       4                 6  4

PS

This script is the very first thing I wrote with Python so pull requests are very welcome :)

Info

If you like this git you can follow me here or on twitter @MarioIannotta

About

A script to evaluate mathematical expression in postfix notation

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages