Some PEP8 rectifications

This commit is contained in:
Bertrand Benjamin 2018-03-13 14:43:48 +03:00
parent e9046c49ff
commit e4efa1028e
14 changed files with 100 additions and 109 deletions

View File

@ -7,7 +7,7 @@
# Distributed under terms of the MIT license. # Distributed under terms of the MIT license.
from mapytex.calculus.core.tree import Tree from mapytex.calculus.core.tree import Tree
from .mo import MO, MOError from .mo import MO
__all__ = ["MOFraction"] __all__ = ["MOFraction"]
@ -33,9 +33,9 @@ class MOFraction(MO):
<MOFraction - 2 / 3> <MOFraction - 2 / 3>
""" """
base_value = Tree("/", base_value = Tree("/",
MO.factory(numerator), MO.factory(numerator),
MO.factory(denominator), MO.factory(denominator),
) )
if negative: if negative:
value = Tree("-", None, base_value) value = Tree("-", None, base_value)
else: else:

View File

@ -6,9 +6,9 @@
# #
# Distributed under terms of the MIT license. # Distributed under terms of the MIT license.
from decimal import Decimal
from ..coroutine import coroutine, STOOOP from ..coroutine import coroutine, STOOOP
from ..renders import tree2txt, tree2tex from ..renders import tree2txt, tree2tex
from decimal import Decimal
__all__ = ["moify", "MO", "MOstr"] __all__ = ["moify", "MO", "MOstr"]
@ -43,23 +43,22 @@ class MO(object):
"""MO for math object """MO for math object
This base class is representing int and Decimal. It stocks its value in This base class is representing int and Decimal. It stocks its value in
self.value and it self.value and it
""" """
def __init__(self, value): def __init__(self, value):
""" Initiate the MO """ Initiate the MO
It should be idempotent. It should be idempotent.
>>> a = MO(3) >>> a = MO(3)
>>> a >>> a
<MO 3> <MO 3>
>>> a = MO(a) >>> a = MO(a)
>>> a >>> a
<MO 3> <MO 3>
""" """
try: try:
self.value = value.value self.value = value.value
@ -107,7 +106,7 @@ class MOnumber(MO):
""" Base number math object (int or Decimal) """ """ Base number math object (int or Decimal) """
def __init__(self, value, negative=False): def __init__(self, value):
""" Initiate a number MO """ Initiate a number MO
>>> MOnumber(23) >>> MOnumber(23)
@ -134,7 +133,7 @@ class MOnumber(MO):
except AttributeError: except AttributeError:
val = value val = value
if isinstance(val, int) or isinstance(val, Decimal): if isinstance(val, (int, Decimal)):
MO.__init__(self, value) MO.__init__(self, value)
elif isinstance(val, float): elif isinstance(val, float):
MO.__init__(self, Decimal(val)) MO.__init__(self, Decimal(val))
@ -154,7 +153,7 @@ class MOnumber(MO):
return str(self.value) return str(self.value)
return f"- {abs(self.value)}" return f"- {abs(self.value)}"
class MOstr(MO): class MOstr(MO):
""" Unknown math object like x or n""" """ Unknown math object like x or n"""
@ -197,7 +196,7 @@ class MOstr(MO):
MO.__init__(self, value) MO.__init__(self, value)
self.is_scalar = False self.is_scalar = False
# ----------------------------- # -----------------------------
# Reglages pour 'vim' # Reglages pour 'vim'
# vim:set autoindent expandtab tabstop=4 shiftwidth=4: # vim:set autoindent expandtab tabstop=4 shiftwidth=4:

View File

@ -10,7 +10,6 @@
Computing with MO Computing with MO
""" """
from ..operator import OPERATORS
from .exceptions import ComputeError from .exceptions import ComputeError
from .add import add from .add import add
from .minus import minus from .minus import minus

View File

@ -11,8 +11,7 @@ Adding MO
""" """
from ..tree import Tree from ..tree import Tree
from ..operator import OPERATORS from ..MO.mo import MO, MOnumber
from ..MO.mo import MO, MOnumber, MOstr
from ..MO.fraction import MOFraction from ..MO.fraction import MOFraction
from .exceptions import AddError from .exceptions import AddError
from .arithmetic import lcm from .arithmetic import lcm
@ -206,11 +205,11 @@ def mofraction_mofraction(left, right):
# TODO: Faire un décorateur pour un enregistrement automatique |dim. mars 11 18:24:32 EAT 2018 # TODO: Faire un décorateur pour un enregistrement automatique |dim. mars 11 18:24:32 EAT 2018
ADDFUNCTIONS = { ADDFUNCTIONS = {
(MOnumber, MOnumber): monumber_monumber, (MOnumber, MOnumber): monumber_monumber,
(MOnumber, MOFraction): monumber_mofraction, (MOnumber, MOFraction): monumber_mofraction,
(MOFraction, MOnumber): mofraction_monumber, (MOFraction, MOnumber): mofraction_monumber,
(MOFraction, MOFraction): mofraction_mofraction, (MOFraction, MOFraction): mofraction_mofraction,
} }
# ----------------------------- # -----------------------------
# Reglages pour 'vim' # Reglages pour 'vim'

View File

@ -22,6 +22,9 @@ class MinusError(ComputeError):
class MultiplyError(ComputeError): class MultiplyError(ComputeError):
pass pass
class DivideError(ComputeError):
pass
# ----------------------------- # -----------------------------
# Reglages pour 'vim' # Reglages pour 'vim'

View File

@ -10,12 +10,9 @@
Minus MO: take the opposit Minus MO: take the opposit
""" """
from ..tree import Tree from ..MO.mo import MO, MOnumber
from ..operator import OPERATORS
from ..MO.mo import MO, MOnumber, MOstr
from ..MO.fraction import MOFraction from ..MO.fraction import MOFraction
from .exceptions import MinusError from .exceptions import MinusError
from .arithmetic import lcm
def minus(left, right): def minus(left, right):
@ -92,9 +89,9 @@ def mofraction(right):
# TODO: Faire un décorateur pour un enregistrement automatique |dim. mars 11 18:24:32 EAT 2018 # TODO: Faire un décorateur pour un enregistrement automatique |dim. mars 11 18:24:32 EAT 2018
MINUSFUNCTIONS = { MINUSFUNCTIONS = {
MOnumber: monumber, MOnumber: monumber,
MOFraction: mofraction, MOFraction: mofraction,
} }
# ----------------------------- # -----------------------------
# Reglages pour 'vim' # Reglages pour 'vim'

View File

@ -11,8 +11,7 @@ Multiply MO
""" """
from ..tree import Tree from ..tree import Tree
from ..operator import OPERATORS from ..MO.mo import MO, MOnumber
from ..MO.mo import MO, MOnumber, MOstr
from ..MO.fraction import MOFraction from ..MO.fraction import MOFraction
from .exceptions import MultiplyError from .exceptions import MultiplyError
@ -116,10 +115,10 @@ def mofraction_monumber(left, right):
# TODO: Faire un décorateur pour un enregistrement automatique |dim. mars 11 18:24:32 EAT 2018 # TODO: Faire un décorateur pour un enregistrement automatique |dim. mars 11 18:24:32 EAT 2018
MULFUNCTIONS = { MULFUNCTIONS = {
(MOnumber, MOnumber): monumber_monumber, (MOnumber, MOnumber): monumber_monumber,
(MOnumber, MOFraction): monumber_mofraction, (MOnumber, MOFraction): monumber_mofraction,
(MOFraction, MOnumber): mofraction_monumber, (MOFraction, MOnumber): mofraction_monumber,
} }
# ----------------------------- # -----------------------------
# Reglages pour 'vim' # Reglages pour 'vim'

View File

@ -16,8 +16,8 @@ __all__ = ["coroutine", "STOOOP", "RESTAAART"]
def coroutine(func): def coroutine(func):
@wraps(func) @wraps(func)
def start(*args,**kwargs): def start(*args, **kwargs):
cr = func(*args,**kwargs) cr = func(*args, **kwargs)
next(cr) next(cr)
return cr return cr
return start return start

View File

@ -12,26 +12,26 @@ class OperatorError(Exception):
pass pass
OPERATORS = { OPERATORS = {
"+": {'repr': "+", "+": {'repr': "+",
'arity': 2, 'arity': 2,
'precedence': 0, 'precedence': 0,
}, },
"-": {'repr': "-", "-": {'repr': "-",
'arity': 1, 'arity': 1,
'precedence': 1, 'precedence': 1,
}, },
"*": {'repr': "*", "*": {'repr': "*",
'arity': 2, 'arity': 2,
'precedence': 2, 'precedence': 2,
}, },
"/": {'repr': "/", "/": {'repr': "/",
'arity': 2, 'arity': 2,
'precedence': 3, 'precedence': 3,
}, },
"^": {'repr': "^", "^": {'repr': "^",
'arity': 2, 'arity': 2,
'precedence': 4, 'precedence': 4,
}, },
} }
def is_operator(string): def is_operator(string):

View File

@ -126,8 +126,7 @@ def mul2tex(left, right):
if display_time: if display_time:
return f"{left_} \\times {right_}" return f"{left_} \\times {right_}"
else: return f"{left_}{right_}"
return f"{left_}{right_}"
def div2tex(left, right): def div2tex(left, right):
r""" / rendering r""" / rendering
@ -199,12 +198,12 @@ def pow2tex(left, right):
return f"{left_} ^ {right_}" return f"{left_} ^ {right_}"
OPERATOR2tex = { OPERATOR2TEX = {
"+": plus2tex, "+": plus2tex,
"-": minus2tex, "-": minus2tex,
"*": mul2tex, "*": mul2tex,
"/": div2tex, "/": div2tex,
"^": pow2tex, "^": pow2tex,
} }
def tree2tex(tree): def tree2tex(tree):
@ -217,7 +216,7 @@ def tree2tex(tree):
>>> tree2tex(t) >>> tree2tex(t)
'2 + 3 \\times 4' '2 + 3 \\times 4'
""" """
return OPERATOR2tex[tree.node](tree.left_value, tree.right_value) return OPERATOR2TEX[tree.node](tree.left_value, tree.right_value)
# ----------------------------- # -----------------------------

View File

@ -214,11 +214,11 @@ def pow2txt(left, right):
return f"{left_} ^ {right_}" return f"{left_} ^ {right_}"
OPERATOR2TXT = { OPERATOR2TXT = {
"+": plus2txt, "+": plus2txt,
"-": minus2txt, "-": minus2txt,
"*": mul2txt, "*": mul2txt,
"/": div2txt, "/": div2txt,
"^": pow2txt, "^": pow2txt,
} }
def tree2txt(tree): def tree2txt(tree):
@ -231,7 +231,7 @@ def tree2txt(tree):
>>> tree2txt(t) >>> tree2txt(t)
'2 + 3 * 4' '2 + 3 * 4'
""" """
return OPERATOR2TXT[tree.node](tree.left_value, tree.right_value) return OPERATOR2TXT[tree.node](tree.left_value, tree.right_value)
# ----------------------------- # -----------------------------

View File

@ -25,7 +25,7 @@ class ParsingError(Exception):
def maybe_it_is(cara): def maybe_it_is(cara):
""" Return a function which return """ Return a function which return
Maybe if cara startwith the argument and True if it is cara Maybe if cara startwith the argument and True if it is cara
:exemple: :exemple:
@ -170,7 +170,7 @@ def lookfor(condition, replace = lambda x:''.join(x)):
ans = "maybe" ans = "maybe"
elif found: elif found:
ans = replace(acc) ans = replace(acc)
acc = [] acc = []
else: else:
ans = False ans = False
acc = [] acc = []
@ -293,8 +293,6 @@ def concurent_broadcast(target, lookfors = []):
lookfors_ = [remember_lookfor(lkf) for lkf in lookfors] lookfors_ = [remember_lookfor(lkf) for lkf in lookfors]
stock = []
ans = []
try: try:
while True: while True:
found = False found = False
@ -310,7 +308,7 @@ def concurent_broadcast(target, lookfors = []):
for lf in lookfors_: for lf in lookfors_:
lf.throw(RESTAAART) lf.throw(RESTAAART)
for i in found: for i in found:
ans = target_.send(i) target_.send(i)
except STOOOP as err: except STOOOP as err:
for lf in lookfors_: for lf in lookfors_:
last = lf.throw(RESTAAART) last = lf.throw(RESTAAART)
@ -320,7 +318,7 @@ def concurent_broadcast(target, lookfors = []):
@coroutine @coroutine
def missing_times(target): def missing_times(target):
""" Coroutine which send a "*" when it's missing """ Coroutine which send a "*" when it's missing
Cases where a "*" is missing: Cases where a "*" is missing:
- 2x or yx or )x - 2x or yx or )x
@ -380,14 +378,14 @@ def missing_times(target):
if not previous is None: if not previous is None:
previous = None previous = None
if type(tok) == str: if isinstance(tok, str):
if tok == '(': if tok == '(':
target_.send("*") target_.send("*")
elif not is_operator(tok) and tok != ')': elif not is_operator(tok) and tok != ')':
target_.send("*") target_.send("*")
if type(tok) == int or \ if isinstance(tok, int) or \
(type(tok) == str and \ (isinstance(tok, str) and \
not is_operator(tok) and \ not is_operator(tok) and \
not tok == '('): not tok == '('):
previous = tok previous = tok
@ -462,7 +460,6 @@ def lookforNumbers(target):
target_ = target target_ = target
current = "" current = ""
ans = []
try: try:
while True: while True:
tok = yield tok = yield
@ -473,12 +470,12 @@ def lookforNumbers(target):
if tok == '.': if tok == '.':
if "." in current: if "." in current:
raise ParsingError(f"Can't build a number with 2 dots (current is {current})") raise ParsingError(f"Can't build a number with 2 dots (current is {current})")
elif len(current) == 0: elif not current:
raise ParsingError(f"Can't build a number starting with a dot") raise ParsingError(f"Can't build a number starting with a dot")
else: else:
current += tok current += tok
elif tok == '-': elif tok == '-':
if len(current) > 0: if current:
target_.send(typifiy_numbers(current)) target_.send(typifiy_numbers(current))
target_.send('+') target_.send('+')
current = tok current = tok
@ -494,9 +491,9 @@ def lookforNumbers(target):
current += tok current += tok
except STOOOP as err: except STOOOP as err:
if current: if current:
target_.send(typifiy_numbers(current)) target_.send(typifiy_numbers(current))
yield target_.throw(err) yield target_.throw(err)
def typifiy_numbers(number): def typifiy_numbers(number):
""" Transform a str number into a integer or a decimal """ """ Transform a str number into a integer or a decimal """
@ -564,7 +561,7 @@ def list_sink():
except STOOOP: except STOOOP:
yield ans yield ans
def str2(sink, convert_to_MO=True): def str2(sink, convert_to_mo=True):
""" Return a pipeline which parse an expression with the sink as an endpont """ Return a pipeline which parse an expression with the sink as an endpont
:example: :example:
@ -685,13 +682,13 @@ def str2(sink, convert_to_MO=True):
""" """
lfop = lookfor(is_operator) lfop = lookfor(is_operator)
operator_corout = partial(concurent_broadcast, lookfors = [lfop]) operator_corout = partial(concurent_broadcast, lookfors=[lfop])
def pipeline(expression): def pipeline(expression):
if convert_to_MO: if convert_to_mo:
str2_corout = lookforNumbers(operator_corout(missing_times(moify(pparser(sink))))) str2_corout = lookforNumbers(operator_corout(missing_times(moify(pparser(sink)))))
else: else:
str2_corout = lookforNumbers(operator_corout(missing_times(pparser(sink)))) str2_corout = lookforNumbers(operator_corout(missing_times(pparser(sink))))
for i in expression: for i in expression:
str2_corout.send(i) str2_corout.send(i)
a = str2_corout.throw(STOOOP) a = str2_corout.throw(STOOOP)

View File

@ -10,11 +10,10 @@ Tree class
""" """
from .tree_tools import (to_nested_parenthesis, from .tree_tools import (to_nested_parenthesis,
infix_str_concatenate, postfix_concatenate,
postfix_concatenate, show_tree,
show_tree, )
) from .coroutine import coroutine, STOOOP
from .coroutine import *
from .str2 import str2 from .str2 import str2
from .operator import OPERATORS from .operator import OPERATORS
@ -55,7 +54,7 @@ class Tree(object):
self.right_value = right_value self.right_value = right_value
@classmethod @classmethod
def from_str(cls, expression, convert_to_MO=True): def from_str(cls, expression, convert_to_mo=True):
""" Initiate a tree from an string expression """ Initiate a tree from an string expression
:example: :example:
@ -83,7 +82,7 @@ class Tree(object):
| > n | > n
""" """
t = MutableTree.from_str(expression, convert_to_MO) t = MutableTree.from_str(expression, convert_to_mo)
return cls.from_any_tree(t) return cls.from_any_tree(t)
@classmethod @classmethod
@ -268,7 +267,7 @@ class Tree(object):
:example: :example:
>>> t = Tree.from_str("3*4+2", convert_to_MO=False) >>> t = Tree.from_str("3*4+2", convert_to_mo=False)
>>> print(t) >>> print(t)
+ +
> * > *
@ -385,7 +384,7 @@ class Tree(object):
return function(self.node, left_value, right_value) return function(self.node, left_value, right_value)
def get_leafs(self, callback = lambda x:x): def get_leafs(self, callback=lambda x:x):
""" Generator which yield all the leaf value of the tree. """ Generator which yield all the leaf value of the tree.
Callback act on every leaf. Callback act on every leaf.
@ -408,7 +407,7 @@ class Tree(object):
except AttributeError: except AttributeError:
yield callback(self.right_value) yield callback(self.right_value)
def get_nodes(self, callback = lambda x:x): def get_nodes(self, callback=lambda x:x):
""" Generator which yield all nodes of the tree. """ Generator which yield all nodes of the tree.
Callback act on every nodes. Callback act on every nodes.
@ -580,7 +579,7 @@ class MutableTree(Tree):
self.right_value = right_value self.right_value = right_value
@classmethod @classmethod
def from_str(cls, expression, convert_to_MO=True): def from_str(cls, expression, convert_to_mo=True):
""" Initiate the MutableTree """ Initiate the MutableTree
:example: :example:
@ -606,8 +605,8 @@ class MutableTree(Tree):
| > -2 | > -2
| > 3 | > 3
""" """
str2mutTree = str2(cls.sink, convert_to_MO) str_2_mut_tree = str2(cls.sink, convert_to_mo)
return str2mutTree(expression) return str_2_mut_tree(expression)
@classmethod @classmethod
@coroutine @coroutine
@ -867,7 +866,7 @@ class AssocialTree(Tree):
:example: :example:
>>> t = Tree.from_str("3*4+2", convert_to_MO=False) >>> t = Tree.from_str("3*4+2", convert_to_mo=False)
>>> print(t) >>> print(t)
+ +
> * > *
@ -938,7 +937,7 @@ class AssocialTree(Tree):
return function(self.node, left_value, right_value) return function(self.node, left_value, right_value)
def get_leafs(self, callback = lambda x:x): def get_leafs(self, callback=lambda x: x):
""" Generator which yield all the leaf value of the tree. """ Generator which yield all the leaf value of the tree.
Callback act on every leaf. Callback act on every leaf.

View File

@ -29,7 +29,7 @@ def to_nested_parenthesis(op, left, right):
def infix_str_concatenate(op, left, right): def infix_str_concatenate(op, left, right):
""" Concatenate arguments placing op on the middle. """ Concatenate arguments placing op on the middle.
:example: :example:
>>> infix_str_concatenate('+', 1, 2) >>> infix_str_concatenate('+', 1, 2)
@ -39,7 +39,7 @@ def infix_str_concatenate(op, left, right):
def postfix_concatenate(op, left, right): def postfix_concatenate(op, left, right):
""" Concatenate arguments placing op on the middle. """ Concatenate arguments placing op on the middle.
:example: :example:
>>> postfix_concatenate('+', 1, 2) >>> postfix_concatenate('+', 1, 2)
@ -61,7 +61,7 @@ def postfix_concatenate(op, left, right):
return left_tokens + right_tokens + [op] return left_tokens + right_tokens + [op]
def show_tree(op, left, right, sep = "|", node_caracter = ">"): def show_tree(op, left, right, sep="|", node_caracter=">"):
""" Shape argument to make nice Tree display """ Shape argument to make nice Tree display
:example: :example: