the stupid postfix evaluator
Project description
postfixcalc
Simple and stupid infix to postfix converter and evaluator.
How does it work
The algorithm is very simple and straightforward
from postfixcalc.pyeval import evaluate
from postfixcalc.parser import (
extract_nums_and_ops,
flatten_nodes,
infix_to_postfix,
make_num,
parse,
relistexpression,
)
evaluate(
infix_to_postfix(
make_num(
relistexpression(
flatten_nodes(
extract_nums_and_ops(
parse('(-1) ^ 2')
),
),
),
),
),
)
We should trace from bottom to top:
- parse the expression using
ast.parse
function. This function will parse the expression based on Python grammar and math op precedence. - extract numbers, and operators outta parsed expression
- the extracted list contains many nested lists and tuples, so we flatten most of them
- we generate a better demonstration outta the flattened list
- we make possible strings to numbers, '-1' will be -1 and ...
- we generate the postfix notation outta the numbers and operators
- evaluate the result
But all this pain is done easily thorough Calc
type in the library
from postfixcalc import Calc
calc = Calc('(-1) ^ 2')
print(calc.answer)
This is easy but Calc
type provide other cached_propertied which are just the results of the upper functions
from postfixcalc import Calc
c = Calc("2 * -1")
print(c.parsed)
print(c.extracted)
print(c.flattened)
print(c.strparenthesized)
print(c.listparenthesized)
print(c.numerized)
print(c.postfix)
print(c.answer)
print(c.stranswer)
# <ast.BinOp object at 0x7fcd313ecbe0>
# [([2], <ast.Mult object at 0x7fcd32002a70>, [(<ast.USub object at 0x7fcd32003010>, [1])])]
# ([2], <ast.Mult object at 0x7fcd32002a70>, (<ast.USub object at 0x7fcd32003010>, [1]))
# 2 * (-1)
# [2, '*', '(', '-1', ')']
# [2, '*', '(', -1, ')']
# [2, -1, '*']
# -2
# -2
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
postfixcalc-0.7.1.tar.gz
(8.9 kB
view hashes)
Built Distribution
Close
Hashes for postfixcalc-0.7.1-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 1e467a16fd20add2b45e5caff7c75b5f9c59e18c31194ba90bdf9e2c6ae1de45 |
|
MD5 | 084b9179d0bfe50e09b535a2d8cea17e |
|
BLAKE2b-256 | 5450d11ad46d9c20308b7a8d924199b24a62ec5e2b2a45bd473b382a905c7e33 |