Mapytex/mapytex/calculus/API/__init__.py

123 lines
2.4 KiB
Python

#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2017 lafrite <lafrite@Poivre>
#
# Distributed under terms of the MIT license.
"""
Generate and compute like a student!
:example:
>>> e = Expression.from_str("2+3*4")
>>> e_simplified = e.simplify()
>>> print(e_simplified)
14
>>> for s in e_simplified.explain():
... print(s)
2 + 3 * 4
2 + 12
14
>>> e = Expression.from_str("2+3/2")
>>> e_simplified = e.simplify()
>>> print(e_simplified)
7 / 2
>>> for s in e_simplified.explain():
... print(s)
2 + 3 / 2
2 / 1 + 3 / 2
(2 * 2) / (1 * 2) + 3 / 2
4 / 2 + 3 / 2
(4 + 3) / 2
7 / 2
>>> e = Expression.from_str("(2+3)/2 + 1")
>>> e_simplified = e.simplify()
>>> print(e_simplified)
7 / 2
>>> for s in e_simplified.explain():
... print(s)
(2 + 3) / 2 + 1
5 / 2 + 1
5 / 2 + 1 / 1
5 / 2 + (1 * 2) / (1 * 2)
5 / 2 + 2 / 2
(5 + 2) / 2
7 / 2
>>> e = Expression.from_str("(2/3)^4")
>>> e_simplified = e.simplify()
>>> print(e_simplified)
16 / 81
>>> for s in e_simplified.explain():
... print(s)
(2 / 3)^4
2^4 / 3^4
16 / 81
>>> e = Expression.from_str("x^2*x*x^4")
>>> e_simplified = e.simplify()
>>> print(e_simplified)
x^7
>>> for s in e_simplified.explain():
... print(s)
x^2 * x * x^4
x^3 * x^4
x^(3 + 4)
x^7
>>> e = Expression.from_str("2x+2+3x")
>>> e_simplified = e.simplify()
>>> print(e_simplified)
5x + 2
>>> for s in e_simplified.explain():
... print(s)
2x + 2 + 3x
2x + 3x + 2
(2 + 3) * x + 2
5x + 2
>>> e = Expression.from_str("2x^2+2x+3x")
>>> e_simplified = e.simplify()
>>> print(e_simplified)
2x^2 + 5x
>>> for s in e_simplified.explain():
... print(s)
2x^2 + 2x + 3x
2x^2 + (2 + 3) * x
2x^2 + 5x
"""
from .expression import Expression
if __name__ == "__main__":
e = Expression.from_str("2x^2+2x+3x")
print(e._tree.map_on_leaf(lambda x:(x,)))
for _ in range(5):
print("-"*10)
e = e._optimize()
try:
print(e._tree.map_on_leaf(lambda x:(x,)))
except AttributeError:
print(e)
e = e._typing()
try:
print(e._tree.map_on_leaf(lambda x:(x,)))
except AttributeError:
print(e)
e = e._compute()
try:
print(e._tree.map_on_leaf(lambda x:(x,)))
except AttributeError:
print(e)
# -----------------------------
# Reglages pour 'vim'
# vim:set autoindent expandtab tabstop=4 shiftwidth=4:
# cursor: 16 del