137 lines
3.0 KiB
Python
137 lines
3.0 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.
|
|
|
|
"""
|
|
Expression
|
|
|
|
"""
|
|
from ..core import Tree, compute
|
|
from .renders import renders
|
|
|
|
class Expression(object):
|
|
|
|
"""
|
|
Expression class
|
|
|
|
:example:
|
|
|
|
>>> e = Expression.from_str("2+3*4")
|
|
>>> e2 = e.simplify()
|
|
>>> print(e2)
|
|
14
|
|
>>> for s in e2.explain():
|
|
... print(s)
|
|
2 + 3 * 4
|
|
2 + 12
|
|
14
|
|
"""
|
|
|
|
RENDER = 'txt'
|
|
|
|
def __init__(self, tree, ancestor=None):
|
|
"""
|
|
"""
|
|
self._tree = tree
|
|
self._ancestor = ancestor
|
|
|
|
@classmethod
|
|
def from_str(cls, string):
|
|
""" Initiate the expression from a string
|
|
|
|
:param string: String to parse to generate the Expression
|
|
:returns: the expression
|
|
|
|
"""
|
|
t = Tree.from_str(string)
|
|
return cls(t)
|
|
|
|
@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
|
|
|
|
@classmethod
|
|
def set_render(cls, render):
|
|
""" Define default render function
|
|
|
|
:param render: render function Tree -> str
|
|
|
|
:example:
|
|
>>> Expression.RENDER
|
|
'txt'
|
|
>>> e = Expression.from_str("2+3*4")
|
|
>>> print(e)
|
|
2 + 3 * 4
|
|
>>> Expression.set_render('tex')
|
|
>>> Expression.RENDER
|
|
'tex'
|
|
>>> print(e)
|
|
2 + 3 \\times 4
|
|
"""
|
|
cls.RENDER = render
|
|
|
|
def __str__(self):
|
|
return renders[self.RENDER](self._tree)
|
|
|
|
def __repr__(self):
|
|
return f"<Exp: {renders[self.RENDER](self._tree)}>"
|
|
|
|
def simplify(self):
|
|
""" Compute as much as possible the expression
|
|
|
|
:return: an expression
|
|
|
|
:example:
|
|
>>> e = Expression.from_str("2+3*4")
|
|
>>> e
|
|
<Exp: 2 + 3 \\times 4>
|
|
>>> f = e.simplify()
|
|
>>> f
|
|
<Exp: 14>
|
|
>>> f._ancestor
|
|
<Exp: 2 + 12>
|
|
"""
|
|
try:
|
|
t = self._tree.apply_on_last_level(compute)
|
|
except AttributeError:
|
|
return self
|
|
else:
|
|
e = Expression(t, ancestor=self)
|
|
return e.simplify()
|
|
|
|
def explain(self):
|
|
""" Yield every calculus step which have lead to self
|
|
|
|
:example:
|
|
>>> e = Expression.from_str("2+3*4")
|
|
>>> f = e.simplify()
|
|
>>> for s in f.explain():
|
|
... print(s)
|
|
2 + 3 * 4
|
|
2 + 12
|
|
14
|
|
"""
|
|
try:
|
|
yield from self._ancestor.explain()
|
|
except AttributeError:
|
|
yield self
|
|
else:
|
|
yield self
|
|
|
|
# -----------------------------
|
|
# Reglages pour 'vim'
|
|
# vim:set autoindent expandtab tabstop=4 shiftwidth=4:
|
|
# cursor: 16 del
|