flake8 corr (not finish yet)

This commit is contained in:
Benjamin Bertrand 2016-03-06 18:18:01 +03:00
parent b6da1e24a1
commit edd83fe56a
14 changed files with 95 additions and 275 deletions

View File

@ -4,8 +4,7 @@
from .explicable import Explicable
from .expression import Expression
from .operator import op
from .generic import spe_zip, expand_list, isNumber, transpose_fill, flatten_list, isPolynom, isNumerand, postfix_op
from .render import txt, tex
from .generic import spe_zip, isNumber, transpose_fill, flatten_list, isPolynom, postfix_op
from functools import wraps
@ -15,7 +14,6 @@ def power_cache(fun):
@wraps(fun)
def cached_fun(self, power):
#print("cache -> ", cache)
if (tuple(self._coef), power) in cache.keys():
return cache[(tuple(self._coef), power)]
else:
@ -346,8 +344,6 @@ class AbstractPolynom(Explicable):
with Expression.tmp_render():
coef_steps += list(coef_exp.simplify().explain())
#print('\t 1.coef_steps -> ', coef_steps)
else:
try:
with Expression.tmp_render():
@ -355,12 +351,9 @@ class AbstractPolynom(Explicable):
except AttributeError:
coef_steps = [coef]
#print('\t 3.coef_steps -> ', coef_steps)
# On ajoute toutes ces étapes
coefs_steps.append(coef_steps)
#print('\t coefs_steps -> ', coefs_steps)
# On retourne la matrice
steps = []
for coefs in transpose_fill(coefs_steps):
@ -586,16 +579,6 @@ class AbstractPolynom(Explicable):
def __xor__(self, power):
return self.__pow__(power)
if __name__ == '__main__':
P = AbstractPolynom([[1, 2], [3, 4, 5], 6])
Q = P.reduce()
for i in Q.explain():
print(i)
#import doctest
# doctest.testmod()
# -----------------------------
# Reglages pour 'vim'
# vim:set autoindent expandtab tabstop=4 shiftwidth=4:

View File

@ -88,8 +88,11 @@ class Explicable(Renderable):
"""
self.steps = steps + self.steps
class Explicable_int(int, Explicable):
""" An Explicable_int is an int which can be explain """
isNumber = True
def __init__(self, val):
@ -107,8 +110,11 @@ class Explicable_int(int, Explicable):
def __tex__(self):
return str(self._val)
class Explicable_Decimal(Decimal, Explicable):
""" An Explicable_Decimal is an decimal which can be explain """
isNumber = True
def __init__(self, val):
@ -127,7 +133,6 @@ class Explicable_Decimal(Decimal, Explicable):
return str(self._val)
# -----------------------------
# Reglages pour 'vim'
# vim:set autoindent expandtab tabstop=4 shiftwidth=4:

View File

@ -4,7 +4,7 @@
# debuging
# from debug.tools import report
from .generic import Stack, flatten_list, expand_list, isNumber, isOperator, isNumerand
from .generic import flatten_list, expand_list, isOperator, isNumerand
from .str2tokens import str2tokens
from .operator import op
from .explicable import Explicable, Explicable_int, Explicable_Decimal
@ -14,6 +14,7 @@ from .random_expression import RdExpression
__all__ = ['Expression']
def pstf_factory(pstf_tokens):
"""Factory which tranform postfix tokens list into an Expression or the simpliest object type ready to be rendered
@ -38,9 +39,7 @@ def pstf_factory(pstf_tokens):
< Fraction 1 / 2>
"""
try:
l_pstf_token = len(pstf_tokens)
except TypeError:
if len(pstf_tokens) == 1:
if isinstance(pstf_tokens[0], int):
return Explicable_int(pstf_tokens[0])
elif isinstance(pstf_tokens[0], Decimal):
@ -49,23 +48,10 @@ def pstf_factory(pstf_tokens):
return Explicable_Decimal(Decimal(str(pstf_tokens[0])))
elif hasattr(pstf_tokens[0], 'STR_RENDER'):
return pstf_tokens[0]
else:
return Expression(self)
else:
if l_pstf_token == 1:
if isinstance(pstf_tokens[0], int):
return Explicable_int(pstf_tokens[0])
elif isinstance(pstf_tokens[0], Decimal):
return Explicable_Decimal(pstf_tokens[0])
elif isinstance(pstf_tokens[0], float):
return Explicable_Decimal(Decimal(str(pstf_tokens[0])))
elif hasattr(pstf_tokens[0], 'STR_RENDER'):
return pstf_tokens[0]
else:
return Expression(self)
else:
return Expression(pstf_tokens)
class Expression(Explicable):
"""A calculus expression. Today it can andle only expression with numbers later it will be able to manipulate unknown"""
@ -84,7 +70,6 @@ class Expression(Explicable):
@classmethod
def tmp_render(cls, render=lambda _, x: pstf_factory(x)):
# def tmp_render(cls, render=lambda _, x: Expression(x)):
""" Same ad tmp_render for Renderable but default render is Expression
>>> exp = Expression("2*3/5")
@ -411,36 +396,10 @@ class Expression(Explicable):
class ExpressionError(Exception):
pass
class ComputeError(Exception):
pass
if __name__ == '__main__':
print('\n')
A = Expression("( -8 x + 8 ) ( -8 - ( -6 x ) )")
Ar = A.simplify()
for i in Ar.explain():
print(i)
# print("------------")
# for i in Ar.explain():
# print(i)
# print(type(Ar))
# print('\n-----------')
#A = Expression("-6 / 3 + 10 / -5")
#Ar = A.simplify()
# for i in Ar.explain():
# print(i)
# print('\n-----------')
#A = Expression("1/3 + 4/6")
#Ar = A.simplify()
# for i in Ar.explain():
# print(i)
#import doctest
# doctest.testmod()
# -----------------------------
# Reglages pour 'vim'
# vim:set autoindent expandtab tabstop=4 shiftwidth=4:

View File

@ -6,7 +6,6 @@ from .generic import isNumber, postfix_op
from .operator import op
from .expression import Expression
from .explicable import Explicable
from .render import txt, tex
from copy import copy
@ -379,7 +378,7 @@ class Fraction(Explicable):
num2 = [number._num]
denom1 = [self._denom]
steps.append(Expression(num1_s + num2_s + [op.mul] + \
steps.append(Expression(num1_s + num2_s + [op.mul] +
denom1_s + denom2_s + [op.mul, op.div]))
exp = Expression(postfix_op(num1 + num2, op.mul, 1) +
@ -527,74 +526,6 @@ class Fraction(Explicable):
return Fraction(self._num, self._denom)
if __name__ == '__main__':
f = Fraction(1, 12)
g = Fraction(6, 12)
for i in g.simplify().explain():
print("g = ", i)
h = Fraction(1, -5)
t = Fraction(10, 3)
print("---------")
for i in (0 + h).explain():
print('0 + h = ', i)
# print("---------")
#print(str(f) , "+", str(t))
# for i in (f + t):
# print(i)
# print("---------")
#print(str(f) , "+", str(g))
# for i in (f + g):
# print(i)
# print("---------")
#print(str(f) , "-", str(g))
# for i in (f - g):
# print(i)
# print("---------")
#print(str(f) , "*", str(g))
# for i in (f * g):
# print(i)
# print("---------")
#print(str(h) , "+", str(t))
# for i in (h + t):
# print(i)
# print("---------")
#print(str(h) , "-", str(t))
# for i in (h - t):
# print(i)
# print("---------")
#print(str(h) , "*", str(t))
# for i in (h * t):
# print(i)
# print("---------")
#print("-", str(h) )
# for i in (-h):
# print(i)
# print("---------")
#print(str(h) , "/", str(t))
# for i in (h / t):
# print(i)
# print("---------")
#print(str(h) , "+", str(0))
# for i in (h + 0):
# print(i)
# print("---------")
#print(str(h) , "*", str(1))
# for i in (h * 1):
# print(i)
# print("---------")
#print(str(h) , "*", str(0))
# for i in (h * 0):
# print(i)
# print("---------")
#print(str(h) , "*", str(4))
# for i in (h * 4):
# print(i)
# print(f.simplify())
import doctest
doctest.testmod()
# -----------------------------
# Reglages pour 'vim'
# vim:set autoindent expandtab tabstop=4 shiftwidth=4:

View File

@ -3,6 +3,7 @@
from .operator import Operator, save_mainOp
class Add(Operator):
r""" The operator +
@ -26,13 +27,13 @@ class Add(Operator):
"""
_CARACT = {
"operator" : "+", \
"name" : "add",\
"priority" : 1, \
"arity" : 2, \
"actions" : ("__add__","__radd__"), \
"txt" : "{op1} + {op2}",\
"tex" : "{op1} + {op2}",\
"operator": "+",
"name": "add",
"priority": 1,
"arity": 2,
"actions": ("__add__", "__radd__"),
"txt": "{op1} + {op2}",
"tex": "{op1} + {op2}",
}
def __init__(self):
@ -63,7 +64,6 @@ class Add(Operator):
return ans
# -----------------------------
# Reglages pour 'vim'
# vim:set autoindent expandtab tabstop=4 shiftwidth=4:

View File

@ -3,6 +3,7 @@
from .operator import Operator, save_mainOp
class Div(Operator):
r""" The operator /
@ -26,12 +27,12 @@ class Div(Operator):
"""
_CARACT = {
"operator" : "/", \
"name" : "div",\
"priority" : 5, \
"arity" : 2, \
"txt" : "{op1} / {op2}",\
"tex" : "\\frac{{ {op1} }}{{ {op2} }}",\
"operator": "/",
"name": "div",
"priority": 5,
"arity": 2,
"txt": "{op1} / {op2}",
"tex": "\\frac{{ {op1} }}{{ {op2} }}",
}
def __init__(self):

View File

@ -4,6 +4,7 @@
from .operator import Operator, save_mainOp
class Mul(Operator):
r""" The operator *
@ -30,13 +31,13 @@ class Mul(Operator):
"""
_CARACT = {
"operator" : "*", \
"name" : "mul",\
"priority" : 4, \
"arity" : 2, \
"actions" : ("__mul__","__rmul__"), \
"txt" : "{op1} * {op2}",\
"tex" : "{op1} \\times {op2}",\
"operator": "*",
"name": "mul",
"priority": 4,
"arity": 2,
"actions": ("__mul__", "__rmul__"),
"txt": "{op1} * {op2}",
"tex": "{op1} \\times {op2}",
}
def __init__(self):
@ -114,9 +115,6 @@ class Mul(Operator):
return ans
# -----------------------------
# Reglages pour 'vim'
# vim:set autoindent expandtab tabstop=4 shiftwidth=4:

View File

@ -3,9 +3,8 @@
# from debug.tools import report
from ..generic import flatten_list, isNumber
from functools import wraps
import types
from ..generic import flatten_list
class Operator():
@ -29,7 +28,6 @@ class Operator():
return getattr(args[0], self.actions)()
elif self.arity == 2:
#if type(args[1]) == int:
if issubclass(type(args[1]), int):
return getattr(args[0], self.actions[0])(args[1])
else:
@ -174,7 +172,7 @@ class Operator():
ans = opl
elif opl.mainOp.priority < self.priority:
ans = flatten_list(["(", opl, ")"])
except AttributeError as e:
except AttributeError:
# op has not the attribute priority
pass
@ -214,6 +212,7 @@ class Operator():
except AttributeError:
return False
def save_mainOp(obj, mainOp):
"""Create a temporary class build over built-in type to stock the main operation of a calculus

View File

@ -2,7 +2,6 @@
# encoding: utf-8
import types
from .add import Add
from .div import Div
from .mul import Mul
@ -72,8 +71,7 @@ class Operator_set(object):
return set([i[0] for i in self._operators])
def can_be_operator(cls, symbole):
r"""
Tell if the symbole can be an operator
r"""Tell if the symbole can be an operator
>>> op = Operator_set()
>>> op.can_be_operator("+")

View File

@ -4,7 +4,6 @@
from .expression import Expression
from .operator import op
from .generic import isNumerand
from .random_expression import RdExpression
from .abstract_polynom import AbstractPolynom
@ -182,8 +181,6 @@ for name, func in inspect.getmembers(Polynom):
setattr(Polynom, name, polynom_factory(func))
# -----------------------------
# Reglages pour 'vim'
# vim:set autoindent expandtab tabstop=4 shiftwidth=4:

View File

@ -242,23 +242,6 @@ class Polynom_deg2(Polynom):
return "\\tkzTabVar{-/{}, +/{$" + str(beta) + "$}, -/{}}"
if __name__ == '__main__':
#from .render import txt
# with Expression.tmp_render(txt):
# P = Polynom_deg2([2, 3, 4])
# print(P)
# print("\nDelta")
# for i in P.delta.explain():
# print(i)
# print("\nBeta")
# for i in P.beta.explain():
# print(i)
import doctest
doctest.testmod()
# -----------------------------
# Reglages pour 'vim'
# vim:set autoindent expandtab tabstop=4 shiftwidth=4:

View File

@ -6,8 +6,6 @@ import re
import pyparsing
from .generic import flatten_list
from .arithmetic import gcd
def random_str(form, conditions=[], val_min=-10, val_max=10):
""" Create a random string using RdExpression class """
@ -41,9 +39,6 @@ class RdExpression(object):
:returns: set for elements which have to be replaced
"""
# pattern = "\{(.*?)\}" #select inside {} non greedy way
#varia_form = re.findall(pattern, self._form)
# TODO: Bug with varia with spaces |dim. nov. 23 10:44:34 CET 2014
varia_form = flatten_list([eval(str(i[0])) for i in pyparsing.nestedExpr(
'{', '}').searchString(self._form)])
@ -157,31 +152,6 @@ def desc_rdExp(rdExp):
print('')
if __name__ == '__main__':
form = "({a};{b})"
cond = []
print(random_str(form, cond))
form = "{a+a*10}*4 + {a} + 2*{b}"
cond = [
"{a} + {b} in [1, 2, 3, 4, 5]",
"abs({a}) not in [1]",
"{b} not in [1]",
"gcd({a},{b}) == 1"]
print(random_str(form, cond))
form = "{a+a*10}*4 + {a} + 2*{b}"
cond = [
"{a-b} + {b} in list(range(20))",
"abs({a}) not in [1]",
"{b} not in [1]",
"gcd({a},{b}) == 1"]
print(random_str(form, cond))
import doctest
doctest.testmod()
# -----------------------------
# Reglages pour 'vim'
# vim:set autoindent expandtab tabstop=4 shiftwidth=4:

View File

@ -56,6 +56,7 @@ def txt_render(token):
txt = Render(txt_render)
def tex_render(token):
def render(*args):
try:
@ -65,6 +66,7 @@ def tex_render(token):
return render
tex = Render(tex_render)
def p2i_render(token):
def render(*args):
try:
@ -74,6 +76,7 @@ def p2i_render(token):
return render
p2i = Render(p2i_render)
class Renderable(object):
"""
A Renderable object is an object which can work with Render class. It means that it has to have attribute postfix_tokens.

View File

@ -1,7 +1,7 @@
#!/usr/bin/env python
# encoding: utf-8
from .generic import Stack, isOperator, isNumber, isPolynom
from .generic import Stack, isNumber, isPolynom
from .operator import op
from decimal import Decimal
@ -70,6 +70,7 @@ def str2in_tokens(exp):
return tokens[2:]
def feed_digit(character, tok_b, tok_bb):
""" Feed token when a digit is detected
@ -117,6 +118,7 @@ def feed_digit(character, tok_b, tok_bb):
else:
return [tok_b, int(character)]
def hidden_meaning_time(tok_b):
""" Return a "*" character if it is hidden meaning
@ -141,6 +143,7 @@ def hidden_meaning_time(tok_b):
return ["*"]
return []
def feed_alpha(character):
""" Feed token when an alpha character is detected
@ -152,6 +155,7 @@ def feed_alpha(character):
from pymath.calculus.polynom import Polynom
return Polynom([0, 1], letter=character)
def feed_dot(tok_b):
r""" Build Decimal with the previous token
@ -202,7 +206,11 @@ def in2post_fix(infix_tokens):
for (pos_token, token) in enumerate(infix_tokens):
logging.debug(str(postfix_tokens)+ " | "+ str(opStack)+ " | "+ str(infix_tokens[(pos_token+1):])+ " | "+ str(arity_Stack))
logging.debug(str(postfix_tokens) +
" | " + str(opStack) +
" | " + str(infix_tokens[(pos_token+1):]) +
" | " + str(arity_Stack)
)
if token == ")":
next_op = opStack.pop()
while next_op != op.par:
@ -238,13 +246,21 @@ def in2post_fix(infix_tokens):
arity = arity_Stack.pop()
arity_Stack.push(arity + 1)
logging.debug(str(postfix_tokens)+ " | "+ str(opStack)+ " | "+ str(infix_tokens[(pos_token+1):])+ " | "+ str(arity_Stack))
logging.debug(str(postfix_tokens) +
" | " + str(opStack) +
" | " + str(infix_tokens[(pos_token+1):]) +
" | " + str(arity_Stack)
)
while not opStack.isEmpty():
next_op = opStack.pop()
postfix_tokens.append(next_op)
logging.debug(str(postfix_tokens)+ " | "+ str(opStack)+ " | "+ str(infix_tokens[(pos_token+1):])+ " | "+ str(arity_Stack))
logging.debug(str(postfix_tokens) +
" | " + str(opStack) +
" | " + str(infix_tokens[(pos_token+1):]) +
" | " + str(arity_Stack)
)
if arity_Stack.peek() != 1:
raise ValueError(
@ -255,29 +271,6 @@ def in2post_fix(infix_tokens):
return postfix_tokens
if __name__ == '__main__':
#a, s, m, d, p = Operator("+"), Operator("-"), Operator("*"), Operator("/"), Operator("^")
#in_tokens = str2in_tokens("2+3*4")
#print("\t in_tokens :" + str(in_tokens))
#
# print(in2post_fix(in_tokens))
#print(in2post_fix([op.par, 2, op.add, 5, op.sub, 1, ')', op.div, op.par, 3, op.mul, 4, ')']))
#print(in2post_fix([op.sub1, op.par, op.sub1, 2, ')']))
#print(in2post_fix([op.sub1, op.par, op.sub1, 2, op.add, 3, op.mul, 4, ')']))
print(str2tokens('2*3+4'))
print("\n------")
print(str2tokens('2x+4'))
print("\n------")
print(str2tokens('xx+4'))
print("\n------")
print(str2tokens('x(2+1)+4'))
print("\n------")
#import doctest
# doctest.testmod()
# -----------------------------
# Reglages pour 'vim'
# vim:set autoindent expandtab tabstop=4 shiftwidth=4: