Mapytex/mapytex/calculus/API/expression.py

91 lines
1.8 KiB
Python
Raw Normal View History

2018-01-21 09:21:13 +00:00
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2017 lafrite <lafrite@Poivre>
#
# Distributed under terms of the MIT license.
"""
Expression
"""
2018-09-17 14:29:00 +00:00
from ..core import Tree, compute, tree2txt, tree2tex
2018-01-21 09:21:13 +00:00
class Expression(object):
"""
Expression class
2018-09-17 14:29:00 +00:00
:example:
>>> e = Expression.from_str("2+3*4")
>>> e2 = e.simplify()
>>> print(e2)
14
>>> e2.explain()
'2 + 3 * 4'
'2 + 12'
'15'
2018-01-21 09:21:13 +00:00
"""
2018-09-17 14:29:00 +00:00
RENDER = tree2txt
def __init__(self, tree):
2018-01-21 09:21:13 +00:00
"""
"""
2018-09-17 14:29:00 +00:00
self._tree = tree
2018-01-21 09:21:13 +00:00
@classmethod
def from_str(cls, string):
""" Initiate the expression from a string
:param string: TODO
:returns: TODO
"""
2018-09-17 14:29:00 +00:00
t = Tree.from_str(string)
return cls(t)
2018-01-21 09:21:13 +00:00
@classmethod
def random(self, template, conditions = [], shuffle = False):
""" Initiate randomly the expression
:param template: the template of the expression
:param conditions: conditions on randomly generate variable
:param shuffle: allowing to shuffle the tree
:returns: TODO
"""
pass
2018-09-17 14:29:00 +00:00
@classmethod
def set_render(cls, render):
""" Define default render function
:param render: render function Tree -> str
:example:
>>> e = Expression.from_str("2+3*4")
>>> print(e)
2 + 3 * 4
>>> Expression.set_render(tree2tex)
>>> print(e)
2 + 3 \\times 4
"""
cls.RENDER = render
def __str__(self):
return self.__class__.RENDER(self._tree)
def __repr__(self):
return f"<Tree {self.__class__.RENDER(self._tree)}>"
2018-01-21 09:21:13 +00:00
# -----------------------------
# Reglages pour 'vim'
# vim:set autoindent expandtab tabstop=4 shiftwidth=4:
# cursor: 16 del