remove trailing spaces

This commit is contained in:
Benjamin Bertrand 2016-02-13 06:29:26 +03:00
parent 52ff23a749
commit b260c838df
29 changed files with 165 additions and 165 deletions

View File

@ -7,4 +7,4 @@ from .stat import Dataset, WeightedDataset
# ----------------------------- # -----------------------------
# Reglages pour 'vim' # Reglages pour 'vim'
# vim:set autoindent expandtab tabstop=4 shiftwidth=4: # vim:set autoindent expandtab tabstop=4 shiftwidth=4:
# cursor: 16 del # cursor: 16 del

View File

@ -11,4 +11,4 @@ from .render import txt
# ----------------------------- # -----------------------------
# Reglages pour 'vim' # Reglages pour 'vim'
# vim:set autoindent expandtab tabstop=4 shiftwidth=4: # vim:set autoindent expandtab tabstop=4 shiftwidth=4:
# cursor: 16 del # cursor: 16 del

View File

@ -71,7 +71,7 @@ class AbstractPolynom(Explicable):
self.feed_coef(coefs) self.feed_coef(coefs)
self._letter = letter self._letter = letter
self.name = name self.name = name
if self.is_monom(): if self.is_monom():
self.mainOp = op.mul self.mainOp = op.mul
else: else:
@ -81,7 +81,7 @@ class AbstractPolynom(Explicable):
def feed_coef(self, l_coef): def feed_coef(self, l_coef):
"""Feed coef of the polynom. Manage differently whether it's a number or an expression """Feed coef of the polynom. Manage differently whether it's a number or an expression
:l_coef: list of coef :l_coef: list of coef
""" """
self._coef = [] self._coef = []
@ -156,16 +156,16 @@ class AbstractPolynom(Explicable):
['x', 2, '^'] ['x', 2, '^']
""" """
ans =[] ans =[]
if a == [0]: if a == [0]:
pass pass
elif i == 0: elif i == 0:
ans = a ans = a
elif i == 1: elif i == 1:
ans = a * (a!=[1]) + [self._letter] + [op.mul] * (a!=[1]) ans = a * (a!=[1]) + [self._letter] + [op.mul] * (a!=[1])
else: else:
ans = a * (a!=[1]) + [self._letter, i, op.pw] + [op.mul] * (a!=[1]) ans = a * (a!=[1]) + [self._letter, i, op.pw] + [op.mul] * (a!=[1])
return ans return ans
@property @property
@ -276,13 +276,13 @@ class AbstractPolynom(Explicable):
def conv2poly(self, other): def conv2poly(self, other):
"""Convert anything number into a polynom """Convert anything number into a polynom
>>> P = AbstractPolynom([1,2,3]) >>> P = AbstractPolynom([1,2,3])
>>> P.conv2poly(1) >>> P.conv2poly(1)
< <class 'pymath.calculus.abstract_polynom.AbstractPolynom'> [1]> < <class 'pymath.calculus.abstract_polynom.AbstractPolynom'> [1]>
>>> P.conv2poly(0) >>> P.conv2poly(0)
< <class 'pymath.calculus.abstract_polynom.AbstractPolynom'> [0]> < <class 'pymath.calculus.abstract_polynom.AbstractPolynom'> [0]>
""" """
if isNumber(other) and not isPolynom(other): if isNumber(other) and not isPolynom(other):
return AbstractPolynom([other], letter = self._letter) return AbstractPolynom([other], letter = self._letter)
@ -290,7 +290,7 @@ class AbstractPolynom(Explicable):
return other return other
else: else:
raise ValueError(type(other) + " can't be converted into a polynom") raise ValueError(type(other) + " can't be converted into a polynom")
def reduce(self): def reduce(self):
"""Compute coefficients which have same degree """Compute coefficients which have same degree
@ -315,7 +315,7 @@ class AbstractPolynom(Explicable):
>>> Q.steps >>> Q.steps
[< <class 'pymath.calculus.abstract_polynom.AbstractPolynom'> [[1, 2], [3, 4, 5], 6]>, < <class 'pymath.calculus.abstract_polynom.AbstractPolynom'> [< <class 'pymath.calculus.expression.Expression'> [1, 2, '+'] >, < <class 'pymath.calculus.expression.Expression'> [3, 4, '+', 5, '+'] >, 6]>, < <class 'pymath.calculus.abstract_polynom.AbstractPolynom'> [3, < <class 'pymath.calculus.expression.Expression'> [7, 5, '+'] >, 6]>] [< <class 'pymath.calculus.abstract_polynom.AbstractPolynom'> [[1, 2], [3, 4, 5], 6]>, < <class 'pymath.calculus.abstract_polynom.AbstractPolynom'> [< <class 'pymath.calculus.expression.Expression'> [1, 2, '+'] >, < <class 'pymath.calculus.expression.Expression'> [3, 4, '+', 5, '+'] >, 6]>, < <class 'pymath.calculus.abstract_polynom.AbstractPolynom'> [3, < <class 'pymath.calculus.expression.Expression'> [7, 5, '+'] >, 6]>]
""" """
# TODO: It doesn't not compute quick enough |ven. févr. 27 18:04:01 CET 2015 # TODO: It doesn't not compute quick enough |ven. févr. 27 18:04:01 CET 2015
# gather steps for every coefficients # gather steps for every coefficients
@ -368,7 +368,7 @@ class AbstractPolynom(Explicable):
ans, steps = steps[-1], steps[:-1] ans, steps = steps[-1], steps[:-1]
ans.steps = steps ans.steps = steps
return ans return ans
def simplify(self): def simplify(self):
@ -378,7 +378,7 @@ class AbstractPolynom(Explicable):
@staticmethod @staticmethod
def postfix_add(numbers): def postfix_add(numbers):
"""Convert a list of numbers into a postfix addition """Convert a list of numbers into a postfix addition
:numbers: list of numbers :numbers: list of numbers
:returns: Postfix list of succecive attition of number :returns: Postfix list of succecive attition of number
@ -400,7 +400,7 @@ class AbstractPolynom(Explicable):
else: else:
ans = [[a, op.add] if i!=0 else [a] for (i,a) in enumerate(numbers)] ans = [[a, op.add] if i!=0 else [a] for (i,a) in enumerate(numbers)]
return list(chain.from_iterable(ans)) return list(chain.from_iterable(ans))
def __eq__(self, other): def __eq__(self, other):
try: try:
o_poly = self.conv2poly(other) o_poly = self.conv2poly(other)
@ -409,7 +409,7 @@ class AbstractPolynom(Explicable):
return 0 return 0
def __add__(self, other): def __add__(self, other):
""" Overload + """ Overload +
>>> P = AbstractPolynom([1,2,3]) >>> P = AbstractPolynom([1,2,3])
>>> Q = AbstractPolynom([4,5]) >>> Q = AbstractPolynom([4,5])
@ -484,9 +484,9 @@ class AbstractPolynom(Explicable):
def __rsub__(self, other): def __rsub__(self, other):
o_poly = self.conv2poly(other) o_poly = self.conv2poly(other)
return o_poly.__sub__(self) return o_poly.__sub__(self)
def __mul__(self, other): def __mul__(self, other):
""" Overload * """ Overload *
@ -549,7 +549,7 @@ class AbstractPolynom(Explicable):
o_poly = self.conv2poly(other) o_poly = self.conv2poly(other)
return o_poly.__mul__(self) return o_poly.__mul__(self)
@power_cache @power_cache
def __pow__(self, power): def __pow__(self, power):
""" Overload ** """ Overload **
@ -612,4 +612,4 @@ if __name__ == '__main__':
# ----------------------------- # -----------------------------
# Reglages pour 'vim' # Reglages pour 'vim'
# vim:set autoindent expandtab tabstop=4 shiftwidth=4: # vim:set autoindent expandtab tabstop=4 shiftwidth=4:
# cursor: 16 del # cursor: 16 del

View File

@ -41,4 +41,4 @@ if __name__ == '__main__':
# ----------------------------- # -----------------------------
# Reglages pour 'vim' # Reglages pour 'vim'
# vim:set autoindent expandtab tabstop=4 shiftwidth=4: # vim:set autoindent expandtab tabstop=4 shiftwidth=4:
# cursor: 16 del # cursor: 16 del

View File

@ -71,23 +71,23 @@ class Renderable(object):
except AttributeError: except AttributeError:
return False return False
class Explicable(Renderable): class Explicable(Renderable):
""" An Explicable object is an object which can be explicable! """ An Explicable object is an object which can be explicable!
It's a parent class of a more classical Expression, Fraction and Polynom (and later square root) It's a parent class of a more classical Expression, Fraction and Polynom (and later square root)
Child class will have the following method Child class will have the following method
* explain: Generator which return steps which leed to himself * explain: Generator which return steps which leed to himself
""" """
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
self.steps = [] self.steps = []
def explain(self, noself = True): def explain(self, noself = True):
""" Generate and render steps which leed to itself """ Generate and render steps which leed to itself
:param noself: does explain return self :param noself: does explain return self
""" """
@ -125,11 +125,11 @@ class Explicable(Renderable):
else: else:
return False return False
# ----------------------------- # -----------------------------
# Reglages pour 'vim' # Reglages pour 'vim'
# vim:set autoindent expandtab tabstop=4 shiftwidth=4: # vim:set autoindent expandtab tabstop=4 shiftwidth=4:
# cursor: 16 del # cursor: 16 del

View File

@ -22,7 +22,7 @@ class Fake_int(int, Explicable):
self.steps = [] self.steps = []
def simplify(self): def simplify(self):
return Fake_int(self._val) return Fake_int(self._val)
class Expression(Explicable): class Expression(Explicable):
"""A calculus expression. Today it can andle only expression with numbers later it will be able to manipulate unknown""" """A calculus expression. Today it can andle only expression with numbers later it will be able to manipulate unknown"""
@ -88,7 +88,7 @@ class Expression(Explicable):
expression = object.__new__(cls) expression = object.__new__(cls)
if type(exp) == str: if type(exp) == str:
expression.postfix_tokens = str2tokens(exp) expression.postfix_tokens = str2tokens(exp)
elif type(exp) == list: elif type(exp) == list:
# Ici on ne peut convertir les "+" en opérateur que s'ils sont d'arité 2. # Ici on ne peut convertir les "+" en opérateur que s'ils sont d'arité 2.
@ -96,7 +96,7 @@ class Expression(Explicable):
expression.postfix_tokens = flatten_list([tok.postfix_tokens if Expression.isExpression(tok) else tok for tok in exp_mod_op]) expression.postfix_tokens = flatten_list([tok.postfix_tokens if Expression.isExpression(tok) else tok for tok in exp_mod_op])
elif type(exp) == Expression: elif type(exp) == Expression:
return exp return exp
elif isNumerand(exp): elif isNumerand(exp):
expression.postfix_tokens = [exp] expression.postfix_tokens = [exp]
@ -156,16 +156,16 @@ class Expression(Explicable):
tokenList = self.postfix_tokens.copy() tokenList = self.postfix_tokens.copy()
tmpTokenList = [] tmpTokenList = []
while len(tokenList) > 2: while len(tokenList) > 2:
# on va chercher les motifs du genre A B +, quand l'operateur est d'arité 2, pour les calculer # on va chercher les motifs du genre A B +, quand l'operateur est d'arité 2, pour les calculer
if isNumerand(tokenList[0]) and isNumerand(tokenList[1]) \ if isNumerand(tokenList[0]) and isNumerand(tokenList[1]) \
and isOperator(tokenList[2]) and tokenList[2].arity == 2 : and isOperator(tokenList[2]) and tokenList[2].arity == 2 :
# S'il y a une opération à faire # S'il y a une opération à faire
op1 = tokenList[0] op1 = tokenList[0]
op2 = tokenList[1] op2 = tokenList[1]
operator = tokenList[2] operator = tokenList[2]
res = operator(op1, op2) res = operator(op1, op2)
tmpTokenList.append(res) tmpTokenList.append(res)
@ -176,7 +176,7 @@ class Expression(Explicable):
# Et les motifs du gens A -, quand l'operateur est d'arité 1 # Et les motifs du gens A -, quand l'operateur est d'arité 1
elif isNumerand(tokenList[0]) \ elif isNumerand(tokenList[0]) \
and isOperator(tokenList[1]) and tokenList[1].arity == 1: and isOperator(tokenList[1]) and tokenList[1].arity == 1:
# S'il y a une opération à faire # S'il y a une opération à faire
op1 = tokenList[0] op1 = tokenList[0]
operator = tokenList[1] operator = tokenList[1]
@ -261,7 +261,7 @@ class Expression(Explicable):
return Expression(self.postfix_tokens + other + [operator]) return Expression(self.postfix_tokens + other + [operator])
else: else:
return Expression(self.postfix_tokens + [other] + [operator]) return Expression(self.postfix_tokens + [other] + [operator])
def roperate(self, other, operator): def roperate(self, other, operator):
if type(other) == Expression: if type(other) == Expression:
return Expression(other.postfix_tokens + self.postfix_tokens + [operator]) return Expression(other.postfix_tokens + self.postfix_tokens + [operator])
@ -336,7 +336,7 @@ class Expression(Explicable):
>>> c = a / b >>> c = a / b
>>> print(c.postfix_tokens) >>> print(c.postfix_tokens)
[1, 2, '+', 3, 4, '+', '/'] [1, 2, '+', 3, 4, '+', '/']
>>> >>>
""" """
return self.operate(other, op.div) return self.operate(other, op.div)
@ -351,7 +351,7 @@ class Expression(Explicable):
def __neg__(self): def __neg__(self):
return Expression(self.postfix_tokens + [op.sub1]) return Expression(self.postfix_tokens + [op.sub1])
def untest(exp): def untest(exp):
a = Expression(exp) a = Expression(exp)
@ -376,7 +376,7 @@ if __name__ == '__main__':
# print(i) # print(i)
#print(type(Ar)) #print(type(Ar))
#print('\n-----------') #print('\n-----------')
#A = Expression("-6 / 3 + 10 / -5") #A = Expression("-6 / 3 + 10 / -5")
@ -396,4 +396,4 @@ if __name__ == '__main__':
# ----------------------------- # -----------------------------
# Reglages pour 'vim' # Reglages pour 'vim'
# vim:set autoindent expandtab tabstop=4 shiftwidth=4: # vim:set autoindent expandtab tabstop=4 shiftwidth=4:
# cursor: 16 del # cursor: 16 del

View File

@ -31,7 +31,7 @@ class Fraction(Explicable):
self.isNumber = 1 self.isNumber = 1
def simplify(self): def simplify(self):
"""Simplify the fraction """Simplify the fraction
:returns: steps to simplify the fraction or the fraction if there is nothing to do :returns: steps to simplify the fraction or the fraction if there is nothing to do
@ -133,7 +133,7 @@ class Fraction(Explicable):
number = Fraction(other) number = Fraction(other)
return number return number
def __add__(self, other): def __add__(self, other):
""" overload + """ overload +
@ -276,7 +276,7 @@ class Fraction(Explicable):
ans = f.simplify() ans = f.simplify()
return ans return ans
def __mul__(self, other): def __mul__(self, other):
""" overload * """ overload *
@ -330,18 +330,18 @@ class Fraction(Explicable):
else: else:
number = self.convert2fraction(other) number = self.convert2fraction(other)
gcd1 = gcd(self._num, number._denom) gcd1 = gcd(self._num, number._denom)
if gcd1 != 1: if gcd1 != 1:
num1 = [int(self._num/ gcd1), gcd1, op.mul] num1 = [int(self._num/ gcd1), gcd1, op.mul]
denom2 = [int(number._denom/ gcd1), gcd1, op.mul] denom2 = [int(number._denom/ gcd1), gcd1, op.mul]
else: else:
num1 = [self._num] num1 = [self._num]
denom2 = [number._denom] denom2 = [number._denom]
gcd2 = gcd(self._denom, number._num) gcd2 = gcd(self._denom, number._num)
if gcd2 != 1: if gcd2 != 1:
num2 = [int(number._num/ gcd2), gcd2, op.mul] num2 = [int(number._num/ gcd2), gcd2, op.mul]
denom1 = [int(self._denom/ gcd2), gcd2, op.mul] denom1 = [int(self._denom/ gcd2), gcd2, op.mul]
else: else:
num2 = [number._num] num2 = [number._num]
denom1 = [self._denom] denom1 = [self._denom]
@ -396,7 +396,7 @@ class Fraction(Explicable):
def __pow__(self, power): def __pow__(self, power):
""" overload ** """ overload **
>>> f = Fraction(3, 4) >>> f = Fraction(3, 4)
>>> f**0 >>> f**0
1 1
@ -419,7 +419,7 @@ class Fraction(Explicable):
< <class 'pymath.calculus.expression.Expression'> [6, 3, '^', 4, 3, '^', '/'] > < <class 'pymath.calculus.expression.Expression'> [6, 3, '^', 4, 3, '^', '/'] >
< <class 'pymath.calculus.expression.Expression'> [216, 64, '/'] > < <class 'pymath.calculus.expression.Expression'> [216, 64, '/'] >
< <class 'pymath.calculus.expression.Expression'> [27, 8, '*', 8, 8, '*', '/'] > < <class 'pymath.calculus.expression.Expression'> [27, 8, '*', 8, 8, '*', '/'] >
""" """
if not type(power) == int: if not type(power) == int:
raise ValueError("Can't raise fraction to power {}".format(str(power))) raise ValueError("Can't raise fraction to power {}".format(str(power)))
@ -449,7 +449,7 @@ class Fraction(Explicable):
>>> f^3 >>> f^3
< Fraction 27 / 64> < Fraction 27 / 64>
""" """
return self.__pow__(power) return self.__pow__(power)
def __abs__(self): def __abs__(self):
@ -557,4 +557,4 @@ if __name__ == '__main__':
# ----------------------------- # -----------------------------
# Reglages pour 'vim' # Reglages pour 'vim'
# vim:set autoindent expandtab tabstop=4 shiftwidth=4: # vim:set autoindent expandtab tabstop=4 shiftwidth=4:
# cursor: 16 del # cursor: 16 del

View File

@ -242,7 +242,7 @@ def convolution_dict(D1, D2, op = lambda x,y:x*y,\
def spe_zip(l1,l2): def spe_zip(l1,l2):
"""Zip two lists, if a list is longer, only it's element are taken """Zip two lists, if a list is longer, only it's element are taken
>>> spe_zip([1,2], [3,4]) >>> spe_zip([1,2], [3,4])
[[1, 3], [2, 4]] [[1, 3], [2, 4]]
>>> spe_zip([1,2], [3,4,5]) >>> spe_zip([1,2], [3,4,5])
@ -260,7 +260,7 @@ def spe_zip(l1,l2):
def transpose_fill(list_lists): def transpose_fill(list_lists):
"""Transpose a list of list and if inside list have not the same length, fill with last token """Transpose a list of list and if inside list have not the same length, fill with last token
:list_lists: a list of list to transpose :list_lists: a list of list to transpose
:returns: generator which generate lines of the transposed matrix :returns: generator which generate lines of the transposed matrix
@ -274,7 +274,7 @@ def transpose_fill(list_lists):
col.append(l[i]) col.append(l[i])
except IndexError: except IndexError:
col.append(l[-1]) col.append(l[-1])
yield col yield col
def isOperator(exp): def isOperator(exp):
@ -284,7 +284,7 @@ def isOperator(exp):
:returns: boolean :returns: boolean
""" """
#return (type(exp) == str and exp in "+-*/:^") #return (type(exp) == str and exp in "+-*/:^")
try: try:
exp.isOperator exp.isOperator
@ -358,4 +358,4 @@ if __name__ == '__main__':
# ----------------------------- # -----------------------------
# Reglages pour 'vim' # Reglages pour 'vim'
# vim:set autoindent expandtab tabstop=4 shiftwidth=4: # vim:set autoindent expandtab tabstop=4 shiftwidth=4:
# cursor: 16 del # cursor: 16 del

View File

@ -66,7 +66,7 @@ class Operator(str):
def __txt__(self, *args): def __txt__(self, *args):
"""Txt rendering for the operator """Txt rendering for the operator
:*args: Operands for this operation :*args: Operands for this operation
:returns: String with operator and his operands :returns: String with operator and his operands
@ -90,7 +90,7 @@ class Operator(str):
def __tex__(self, *args): def __tex__(self, *args):
"""Tex rendering for the operator """Tex rendering for the operator
:*args: Operands for this operation :*args: Operands for this operation
:returns: String with operator and his operands :returns: String with operator and his operands
@ -114,7 +114,7 @@ class Operator(str):
def __p2i__(self, *args): def __p2i__(self, *args):
"""Fix list transformation for the operator """Fix list transformation for the operator
:*args: Operands for this operation :*args: Operands for this operation
:returns: list with the operator surrounded by operands :returns: list with the operator surrounded by operands
@ -140,7 +140,7 @@ class Operator(str):
op1 = self.l_parenthesis(args[0]) op1 = self.l_parenthesis(args[0])
op2 = self.r_parenthesis(args[1]) op2 = self.r_parenthesis(args[1])
ans = flatten_list([op1, self, op2]) ans = flatten_list([op1, self, op2])
ans = save_mainOp(ans, self) ans = save_mainOp(ans, self)
return ans return ans
@ -181,7 +181,7 @@ class Operator(str):
def save_mainOp(obj, mainOp): def save_mainOp(obj, mainOp):
"""Create a temporary class build over built-in type to stock the main operation of a calculus """Create a temporary class build over built-in type to stock the main operation of a calculus
:obj: the object to add the attribute :obj: the object to add the attribute
:mainOp: the main operator :mainOp: the main operator
:returns: the same object with the main operation attribute :returns: the same object with the main operation attribute
@ -251,9 +251,9 @@ class op(object):
@operatorize @operatorize
def add(cls): def add(cls):
""" The operator + """ The operator +
For doctest see test/test_operator.py For doctest see test/test_operator.py
""" """
def _render(self, link, *args): def _render(self, link, *args):
@ -296,7 +296,7 @@ class op(object):
@operatorize @operatorize
def sub(self): def sub(self):
""" The operator - """ The operator -
>>> sub = op.sub >>> sub = op.sub
>>> sub >>> sub
'-' '-'
@ -350,7 +350,7 @@ class op(object):
@operatorize @operatorize
def sub1(self): def sub1(self):
""" The operator - """ The operator -
>>> sub1 = op.sub1 >>> sub1 = op.sub1
>>> sub1 >>> sub1
'-' '-'
@ -398,7 +398,7 @@ class op(object):
@operatorize @operatorize
def mul(self): def mul(self):
""" The operator * """ The operator *
>>> mul = op.mul >>> mul = op.mul
>>> mul >>> mul
'*' '*'
@ -475,7 +475,7 @@ class op(object):
@operatorize @operatorize
def div(self): def div(self):
""" The operator / """ The operator /
>>> div = op.div >>> div = op.div
>>> div >>> div
'/' '/'
@ -498,7 +498,7 @@ class op(object):
def __tex__(self, *args): def __tex__(self, *args):
# Pas besoin de parenthèses en plus pour \frac # Pas besoin de parenthèses en plus pour \frac
replacement = {"op"+str(i+1): op for (i,op) in enumerate(args)} replacement = {"op"+str(i+1): op for (i,op) in enumerate(args)}
ans = self.tex.format(**replacement) ans = self.tex.format(**replacement)
ans = save_mainOp(ans, self) ans = save_mainOp(ans, self)
return ans return ans
@ -520,7 +520,7 @@ class op(object):
@operatorize @operatorize
def pw(self): def pw(self):
""" The operator ^ """ The operator ^
>>> pw = op.pw >>> pw = op.pw
>>> pw >>> pw
'^' '^'
@ -586,7 +586,7 @@ class op(object):
@classmethod @classmethod
def get_op(cls, op, arity = 2): def get_op(cls, op, arity = 2):
"""Return the corresponding operator """Return the corresponding operator
:op: symbole of the op :op: symbole of the op
:arity: the arity :arity: the arity
@ -643,4 +643,4 @@ if __name__ == '__main__':
# ----------------------------- # -----------------------------
# Reglages pour 'vim' # Reglages pour 'vim'
# vim:set autoindent expandtab tabstop=4 shiftwidth=4: # vim:set autoindent expandtab tabstop=4 shiftwidth=4:
# cursor: 16 del # cursor: 16 del

View File

@ -34,7 +34,7 @@ def polynom_factory(func):
class Polynom(AbstractPolynom): class Polynom(AbstractPolynom):
"""Polynom view as a function. """Polynom view as a function.
It can be initiate like a AbstractPolynom It can be initiate like a AbstractPolynom
# Put example # Put example
Randomly Randomly
@ -48,10 +48,10 @@ class Polynom(AbstractPolynom):
@classmethod @classmethod
def random(self, coefs_form=[], conditions=[], letter = "x", degree = 0, name = "P"): def random(self, coefs_form=[], conditions=[], letter = "x", degree = 0, name = "P"):
""" Create a random polynom from coefs_form and conditions """ Create a random polynom from coefs_form and conditions
:param coefs_form: list of forms (one by coef) (ascending degree sorted) :param coefs_form: list of forms (one by coef) (ascending degree sorted)
:param conditions: condition on variables :param conditions: condition on variables
:param letter: the letter for the polynom :param letter: the letter for the polynom
:param degree: degree of the polynom (can't be used with coefs_form, it will be overwrite) - can't be higher than 26 (number of letters in alphabet) :param degree: degree of the polynom (can't be used with coefs_form, it will be overwrite) - can't be higher than 26 (number of letters in alphabet)
@ -146,8 +146,8 @@ class Polynom(AbstractPolynom):
return Expression(postfix_exp).simplify() return Expression(postfix_exp).simplify()
def derivate(self): def derivate(self):
""" Return the derivated polynom """ Return the derivated polynom
>>> P = Polynom([1, 2, 3]) >>> P = Polynom([1, 2, 3])
>>> Q = P.derivate() >>> Q = P.derivate()
>>> Q >>> Q
@ -169,7 +169,7 @@ class Polynom(AbstractPolynom):
# Decorate methods which may return Polynoms # Decorate methods which may return Polynoms
methods_list = ["__add__", "__call__", "__mul__", "__neg__", "__pow__", methods_list = ["__add__", "__call__", "__mul__", "__neg__", "__pow__",
"__radd__", "__rmul__", "__rsub__", "__sub__", "derivate", "__radd__", "__rmul__", "__rsub__", "__sub__", "derivate",
"reduce", "simplify", "random"] "reduce", "simplify", "random"]
for name, func in inspect.getmembers(Polynom): for name, func in inspect.getmembers(Polynom):
if name in methods_list: if name in methods_list:
@ -228,7 +228,7 @@ if __name__ == '__main__':
print("-----------------\n") print("-----------------\n")
f = Fraction(2,3) f = Fraction(2,3)
print(P(f)) print(P(f))
#coefs_p = [[(i-2),(j-2)] for i,j in permutations(range(20),2)] #coefs_p = [[(i-2),(j-2)] for i,j in permutations(range(20),2)]
#fractions = [Fraction(i,j) for i,j in coefs_p if j!=0] #fractions = [Fraction(i,j) for i,j in coefs_p if j!=0]
#for f in fractions: #for f in fractions:
# try: # try:
@ -241,4 +241,4 @@ if __name__ == '__main__':
# ----------------------------- # -----------------------------
# Reglages pour 'vim' # Reglages pour 'vim'
# vim:set autoindent expandtab tabstop=4 shiftwidth=4: # vim:set autoindent expandtab tabstop=4 shiftwidth=4:
# cursor: 16 del # cursor: 16 del

View File

@ -23,7 +23,7 @@ class Polynom_deg2(Polynom):
""" Create a 2nd degree poly from coefs_form ans conditions """ Create a 2nd degree poly from coefs_form ans conditions
:param coefs_form: list of forms (one by coef) (ascending degree sorted) :param coefs_form: list of forms (one by coef) (ascending degree sorted)
:param conditions: condition on variables :param conditions: condition on variables
:param letter: the letter for the polynom :param letter: the letter for the polynom
""" """
@ -83,7 +83,7 @@ class Polynom_deg2(Polynom):
@property @property
def alpha(self): def alpha(self):
""" Compute alpha the abcisse of the extremum """ Compute alpha the abcisse of the extremum
>>> P = Polynom_deg2([1,2,3]) >>> P = Polynom_deg2([1,2,3])
>>> P.alpha >>> P.alpha
< Fraction -1 / 3> < Fraction -1 / 3>
@ -240,11 +240,11 @@ if __name__ == '__main__':
import doctest import doctest
doctest.testmod() doctest.testmod()
# ----------------------------- # -----------------------------
# Reglages pour 'vim' # Reglages pour 'vim'
# vim:set autoindent expandtab tabstop=4 shiftwidth=4: # vim:set autoindent expandtab tabstop=4 shiftwidth=4:
# cursor: 16 del # cursor: 16 del

View File

@ -50,11 +50,11 @@ class RdExpression(object):
for c in self._conditions: for c in self._conditions:
c_varia_cond = flatten_list([eval(str(i[0])) for i in pyparsing.nestedExpr('{','}').searchString(c)]) c_varia_cond = flatten_list([eval(str(i[0])) for i in pyparsing.nestedExpr('{','}').searchString(c)])
varia_cond = varia_cond | set(c_varia_cond) varia_cond = varia_cond | set(c_varia_cond)
self._2replaced = varia_cond | varia_form self._2replaced = varia_cond | varia_form
return self._2replaced return self._2replaced
def get_letters(self): def get_letters(self):
"""Find letters in the form """Find letters in the form
:returns: list of letters :returns: list of letters
@ -90,7 +90,7 @@ class RdExpression(object):
:param val_min: minimum value random generation :param val_min: minimum value random generation
:param val_max: maximum value random generation :param val_max: maximum value random generation
:returns: an formated random expression :returns: an formated random expression
""" """
return self.raw_str(val_min, val_max) return self.raw_str(val_min, val_max)
@ -171,4 +171,4 @@ if __name__ == '__main__':
# ----------------------------- # -----------------------------
# Reglages pour 'vim' # Reglages pour 'vim'
# vim:set autoindent expandtab tabstop=4 shiftwidth=4: # vim:set autoindent expandtab tabstop=4 shiftwidth=4:
# cursor: 16 del # cursor: 16 del

View File

@ -10,7 +10,7 @@ class Render(object):
def __init__(self, render): def __init__(self, render):
"""Initiate the render """Initiate the render
:param render: function which take an operator and return a function to render the operator with his operands :param render: function which take an operator and return a function to render the operator with his operands
""" """
self.render = render self.render = render
@ -25,12 +25,12 @@ class Render(object):
""" """
operandeStack = Stack() operandeStack = Stack()
for token in postfix_tokens: for token in postfix_tokens:
if isOperator(token): if isOperator(token):
if token.arity == 1: if token.arity == 1:
op1 = operandeStack.pop() op1 = operandeStack.pop()
operandeStack.push(self.render(token)(op1)) operandeStack.push(self.render(token)(op1))
elif token.arity == 2: elif token.arity == 2:
op1 = operandeStack.pop() op1 = operandeStack.pop()
@ -76,21 +76,21 @@ if __name__ == '__main__':
from .operator import op from .operator import op
from itertools import permutations from itertools import permutations
from pymath import Polynom from pymath import Polynom
from pymath import Expression from pymath import Expression
from pymath import Fraction from pymath import Fraction
coefs_p = [[(i-2),(j-2)] for i,j in permutations(range(5),2)] coefs_p = [[(i-2),(j-2)] for i,j in permutations(range(5),2)]
coefs_q = [[2*(i-2),2*(j-2)] for i,j in permutations(range(5),2)] coefs_q = [[2*(i-2),2*(j-2)] for i,j in permutations(range(5),2)]
l_p = [Polynom(i) for i in coefs_p] l_p = [Polynom(i) for i in coefs_p]
l_q = [Fraction(i,j) for i,j in coefs_q if j!=0] l_q = [Fraction(i,j) for i,j in coefs_q if j!=0]
operations = [Expression([l_p[i],l_q[j],op.mul]) for i,j in permutations(range(len(l_q)),2)] operations = [Expression([l_p[i],l_q[j],op.mul]) for i,j in permutations(range(len(l_q)),2)]
for i in operations: for i in operations:
print(i) print(i)
# ----------------------------- # -----------------------------
# Reglages pour 'vim' # Reglages pour 'vim'
# vim:set autoindent expandtab tabstop=4 shiftwidth=4: # vim:set autoindent expandtab tabstop=4 shiftwidth=4:
# cursor: 16 del # cursor: 16 del

View File

@ -6,7 +6,7 @@ from .operator import op
def str2tokens(exp): def str2tokens(exp):
""" Parse the string into tokens then turn it into postfix form """ Parse the string into tokens then turn it into postfix form
>>> str2tokens('2+3*4') >>> str2tokens('2+3*4')
[2, 3, 4, '*', '+'] [2, 3, 4, '*', '+']
>>> str2tokens('2*3+4') >>> str2tokens('2*3+4')
@ -86,7 +86,7 @@ def str2in_tokens(exp):
def in2post_fix(infix_tokens): def in2post_fix(infix_tokens):
""" From the infix_tokens list compute the corresponding postfix_tokens list """ From the infix_tokens list compute the corresponding postfix_tokens list
@param infix_tokens: the infix list of tokens to transform into postfix form. @param infix_tokens: the infix list of tokens to transform into postfix form.
@return: the corresponding postfix list of tokens. @return: the corresponding postfix list of tokens.
@ -115,7 +115,7 @@ def in2post_fix(infix_tokens):
postfix_tokens.append(next_op) postfix_tokens.append(next_op)
next_op = opStack.pop() next_op = opStack.pop()
# Go back to old arity # Go back to old arity
arity_Stack.pop() arity_Stack.pop()
# Raise the arity # Raise the arity
arity = arity_Stack.pop() arity = arity_Stack.pop()
@ -127,7 +127,7 @@ def in2post_fix(infix_tokens):
# Set next arity counter # Set next arity counter
arity_Stack.push(0) arity_Stack.push(0)
else: else:
arity = arity_Stack.pop() arity = arity_Stack.pop()
token_op = op.get_op(token, arity + 1) token_op = op.get_op(token, arity + 1)
# Reset arity to 0 in case there is other operators (the real operation would be "-op.arity + 1") # Reset arity to 0 in case there is other operators (the real operation would be "-op.arity + 1")
arity_Stack.push(0) arity_Stack.push(0)
@ -185,4 +185,4 @@ if __name__ == '__main__':
# ----------------------------- # -----------------------------
# Reglages pour 'vim' # Reglages pour 'vim'
# vim:set autoindent expandtab tabstop=4 shiftwidth=4: # vim:set autoindent expandtab tabstop=4 shiftwidth=4:
# cursor: 16 del # cursor: 16 del

View File

@ -28,5 +28,5 @@ def test_gcd_neg():
# ----------------------------- # -----------------------------
# Reglages pour 'vim' # Reglages pour 'vim'
# vim:set autoindent expandtab tabstop=4 shiftwidth=4: # vim:set autoindent expandtab tabstop=4 shiftwidth=4:
# cursor: 16 del # cursor: 16 del

View File

@ -70,11 +70,11 @@ def test_mul_exp():
def test_neg_exp(): def test_neg_exp():
e = Expression("12- 4") e = Expression("12- 4")
g = -e g = -e
assert g.postfix_tokens == [12, 4, '-', '-'] assert g.postfix_tokens == [12, 4, '-', '-']
# ----------------------------- # -----------------------------
# Reglages pour 'vim' # Reglages pour 'vim'
# vim:set autoindent expandtab tabstop=4 shiftwidth=4: # vim:set autoindent expandtab tabstop=4 shiftwidth=4:
# cursor: 16 del # cursor: 16 del

View File

@ -80,7 +80,7 @@ class TestFraction(unittest.TestCase):
f = Fraction(2, 3) f = Fraction(2, 3)
ans = "\\frac{ 2 }{ 3 }" ans = "\\frac{ 2 }{ 3 }"
self.assertEqual(f.__tex__(), ans) self.assertEqual(f.__tex__(), ans)
def test_txt(self): def test_txt(self):
f = Fraction(2, 3) f = Fraction(2, 3)
ans = "2 / 3" ans = "2 / 3"
@ -92,4 +92,4 @@ if __name__ == '__main__':
# ----------------------------- # -----------------------------
# Reglages pour 'vim' # Reglages pour 'vim'
# vim:set autoindent expandtab tabstop=4 shiftwidth=4: # vim:set autoindent expandtab tabstop=4 shiftwidth=4:
# cursor: 16 del # cursor: 16 del

View File

@ -66,11 +66,11 @@ class TestGeneric(unittest.TestCase):
if __name__ == '__main__': if __name__ == '__main__':
unittest.main() unittest.main()
# ----------------------------- # -----------------------------
# Reglages pour 'vim' # Reglages pour 'vim'
# vim:set autoindent expandtab tabstop=4 shiftwidth=4: # vim:set autoindent expandtab tabstop=4 shiftwidth=4:
# cursor: 16 del # cursor: 16 del

View File

@ -84,5 +84,5 @@ def test_pw_render_txt():
# ----------------------------- # -----------------------------
# Reglages pour 'vim' # Reglages pour 'vim'
# vim:set autoindent expandtab tabstop=4 shiftwidth=4: # vim:set autoindent expandtab tabstop=4 shiftwidth=4:
# cursor: 16 del # cursor: 16 del

View File

@ -185,5 +185,5 @@ if __name__ == '__main__':
# ----------------------------- # -----------------------------
# Reglages pour 'vim' # Reglages pour 'vim'
# vim:set autoindent expandtab tabstop=4 shiftwidth=4: # vim:set autoindent expandtab tabstop=4 shiftwidth=4:
# cursor: 16 del # cursor: 16 del

View File

@ -27,5 +27,5 @@ if __name__ == '__main__':
# ----------------------------- # -----------------------------
# Reglages pour 'vim' # Reglages pour 'vim'
# vim:set autoindent expandtab tabstop=4 shiftwidth=4: # vim:set autoindent expandtab tabstop=4 shiftwidth=4:
# cursor: 16 del # cursor: 16 del

View File

@ -14,8 +14,8 @@ def test_only_form():
assert rdExp._2replaced == {'a'} assert rdExp._2replaced == {'a'}
rdExp() rdExp()
assert set(rdExp._gene_varia.keys()) == {'a'} assert set(rdExp._gene_varia.keys()) == {'a'}
assert set(rdExp._gene_2replaced.keys()) == {'a'} assert set(rdExp._gene_2replaced.keys()) == {'a'}
def test_form_with_underscores(): def test_form_with_underscores():
form = "_ + 2*_" form = "_ + 2*_"
@ -25,8 +25,8 @@ def test_form_with_underscores():
assert rdExp._2replaced == {'A', 'B'} assert rdExp._2replaced == {'A', 'B'}
rdExp() rdExp()
assert set(rdExp._gene_varia.keys()) == {'A', 'B'} assert set(rdExp._gene_varia.keys()) == {'A', 'B'}
assert set(rdExp._gene_2replaced.keys()) == {'A', 'B'} assert set(rdExp._gene_2replaced.keys()) == {'A', 'B'}
def test_only_form_calc(): def test_only_form_calc():
form = "{a+b} + 2" form = "{a+b} + 2"
@ -36,8 +36,8 @@ def test_only_form_calc():
assert rdExp._2replaced == {'a+b'} assert rdExp._2replaced == {'a+b'}
rdExp() rdExp()
assert set(rdExp._gene_varia.keys()), {'a' == 'b'} assert set(rdExp._gene_varia.keys()), {'a' == 'b'}
assert set(rdExp._gene_2replaced.keys()) == {'a+b'} assert set(rdExp._gene_2replaced.keys()) == {'a+b'}
def test_only_form_cond(): def test_only_form_cond():
form = "{a} + 2" form = "{a} + 2"
@ -48,8 +48,8 @@ def test_only_form_cond():
assert rdExp._2replaced == {'a'} assert rdExp._2replaced == {'a'}
rdExp() rdExp()
assert set(rdExp._gene_varia.keys()) == {'a'} assert set(rdExp._gene_varia.keys()) == {'a'}
assert set(rdExp._gene_2replaced.keys()) == {'a'} assert set(rdExp._gene_2replaced.keys()) == {'a'}
assert rdExp._gene_varia['a'] == 3 assert rdExp._gene_varia['a'] == 3
@ -62,8 +62,8 @@ def test_only_form_conds():
assert rdExp._2replaced == {'a'} assert rdExp._2replaced == {'a'}
rdExp() rdExp()
assert set(rdExp._gene_varia.keys()) == {'a'} assert set(rdExp._gene_varia.keys()) == {'a'}
assert set(rdExp._gene_2replaced.keys()) == {'a'} assert set(rdExp._gene_2replaced.keys()) == {'a'}
assert rdExp._gene_varia['a'] in list(range(5)) assert rdExp._gene_varia['a'] in list(range(5))
assert rdExp._gene_varia['a'] % 2 == 1 assert rdExp._gene_varia['a'] % 2 == 1
@ -77,8 +77,8 @@ def test_only_form_calc_cond():
assert rdExp._2replaced, {'a', 'b' == 'a*3'} assert rdExp._2replaced, {'a', 'b' == 'a*3'}
rdExp() rdExp()
assert set(rdExp._gene_varia.keys()), {'a' == 'b'} assert set(rdExp._gene_varia.keys()), {'a' == 'b'}
assert set(rdExp._gene_2replaced.keys()), {'a', 'b' == 'a*3'} assert set(rdExp._gene_2replaced.keys()), {'a', 'b' == 'a*3'}
assert rdExp._gene_varia['a'] == 3 assert rdExp._gene_varia['a'] == 3
@ -91,8 +91,8 @@ def test_only_form_calc_cond_calc():
assert rdExp._2replaced, {'b', 'a*3' == 'a+b'} assert rdExp._2replaced, {'b', 'a*3' == 'a+b'}
rdExp() rdExp()
assert set(rdExp._gene_varia.keys()), {'a' == 'b'} assert set(rdExp._gene_varia.keys()), {'a' == 'b'}
assert set(rdExp._gene_2replaced.keys()), {'b', 'a*3' == 'a+b'} assert set(rdExp._gene_2replaced.keys()), {'b', 'a*3' == 'a+b'}
assert (rdExp._gene_varia['a'] + rdExp._gene_varia['b']) == 3 assert (rdExp._gene_varia['a'] + rdExp._gene_varia['b']) == 3
@ -101,5 +101,5 @@ def test_only_form_calc_cond_calc():
# ----------------------------- # -----------------------------
# Reglages pour 'vim' # Reglages pour 'vim'
# vim:set autoindent expandtab tabstop=4 shiftwidth=4: # vim:set autoindent expandtab tabstop=4 shiftwidth=4:
# cursor: 16 del # cursor: 16 del

View File

@ -20,8 +20,8 @@ def mass_poly_test(operation, rg= 5):
:rg: number of potential values for coefs :rg: number of potential values for coefs
:returns: @todo :returns: @todo
""" """
coefs_p = [[(i-2),(j-2)] for i,j in permutations(range(rg),2)] coefs_p = [[(i-2),(j-2)] for i,j in permutations(range(rg),2)]
coefs_q = [[2*(i-2),2*(j-2)] for i,j in permutations(range(rg),2)] coefs_q = [[2*(i-2),2*(j-2)] for i,j in permutations(range(rg),2)]
l_p = [Polynom(i) for i in coefs_p] l_p = [Polynom(i) for i in coefs_p]
l_q = [Polynom(i) for i in coefs_q] l_q = [Polynom(i) for i in coefs_q]
return [Expression([l_p[i],l_q[j],op.get_op(operation)]) for i,j in permutations(range(len(coefs_p)),2)] return [Expression([l_p[i],l_q[j],op.get_op(operation)]) for i,j in permutations(range(len(coefs_p)),2)]
@ -306,5 +306,5 @@ if __name__ == '__main__':
# ----------------------------- # -----------------------------
# Reglages pour 'vim' # Reglages pour 'vim'
# vim:set autoindent expandtab tabstop=4 shiftwidth=4: # vim:set autoindent expandtab tabstop=4 shiftwidth=4:
# cursor: 16 del # cursor: 16 del

View File

@ -13,20 +13,20 @@ class TestStr2tokens(unittest.TestCase):
def test_str2intokens(self): def test_str2intokens(self):
ans = str2in_tokens("2+3*4") ans = str2in_tokens("2+3*4")
self.assertEqual(ans, [2, "+", 3, "*", 4]) self.assertEqual(ans, [2, "+", 3, "*", 4])
ans = str2in_tokens("2*3+4") ans = str2in_tokens("2*3+4")
self.assertEqual(ans, [2, "*", 3, "+", 4]) self.assertEqual(ans, [2, "*", 3, "+", 4])
def test_in2post_fix(self): def test_in2post_fix(self):
in_tokens = str2in_tokens("2+3*4") in_tokens = str2in_tokens("2+3*4")
ans = in2post_fix(in_tokens) ans = in2post_fix(in_tokens)
self.assertEqual(ans, [2, 3, 4, "*", "+"]) self.assertEqual(ans, [2, 3, 4, "*", "+"])
in_tokens = str2in_tokens("2*3+4") in_tokens = str2in_tokens("2*3+4")
ans = in2post_fix(in_tokens) ans = in2post_fix(in_tokens)
self.assertEqual(ans, [2, 3,"*", 4, "+"]) self.assertEqual(ans, [2, 3,"*", 4, "+"])
# TODO: Ajouter des tests pour les cas particuliers... |sam. nov. 8 17:39:18 CET 2014 # TODO: Ajouter des tests pour les cas particuliers... |sam. nov. 8 17:39:18 CET 2014
def test_str2in_tokens_big_num(self): def test_str2in_tokens_big_num(self):
@ -82,5 +82,5 @@ if __name__ == '__main__':
# ----------------------------- # -----------------------------
# Reglages pour 'vim' # Reglages pour 'vim'
# vim:set autoindent expandtab tabstop=4 shiftwidth=4: # vim:set autoindent expandtab tabstop=4 shiftwidth=4:
# cursor: 16 del # cursor: 16 del

View File

@ -7,4 +7,4 @@ from .weightedDataset import WeightedDataset
# ----------------------------- # -----------------------------
# Reglages pour 'vim' # Reglages pour 'vim'
# vim:set autoindent expandtab tabstop=4 shiftwidth=4: # vim:set autoindent expandtab tabstop=4 shiftwidth=4:
# cursor: 16 del # cursor: 16 del

View File

@ -15,7 +15,7 @@ from .random_generator import random_generator
class Dataset(list): class Dataset(list):
""" A dataset (a list) with statistics and latex rendering methods """ A dataset (a list) with statistics and latex rendering methods
>>> s = Dataset(range(100)) >>> s = Dataset(range(100))
>>> s.sum() >>> s.sum()
4950 4950
@ -52,11 +52,11 @@ class Dataset(list):
exact_mean) exact_mean)
return cls(data, data_name = data_name) return cls(data, data_name = data_name)
def __init__(self, data = [], data_name = "Valeurs"): def __init__(self, data = [], data_name = "Valeurs"):
""" """
Create a numeric data set Create a numeric data set
:param data: values of the data set :param data: values of the data set
:param data_name: name of the data set :param data_name: name of the data set
""" """
@ -83,10 +83,10 @@ class Dataset(list):
@number_factory @number_factory
def sum(self): def sum(self):
return sum(self) return sum(self)
@number_factory @number_factory
def mean(self): def mean(self):
return self.sum()/self.effectif_total() return self.sum()/self.effectif_total()
@number_factory @number_factory
def deviation(self): def deviation(self):
@ -97,7 +97,7 @@ class Dataset(list):
@number_factory @number_factory
def variance(self): def variance(self):
return self.deviation()/self.effectif_total() return self.deviation()/self.effectif_total()
@number_factory @number_factory
def sd(self): def sd(self):
""" Compute the standard deviation """ """ Compute the standard deviation """
@ -150,18 +150,18 @@ class Dataset(list):
return self[ceil(position)] return self[ceil(position)]
def posi_quartile(self, quartile = 1): def posi_quartile(self, quartile = 1):
""" """
Calcul la position du quartile Calcul la position du quartile
:param quartile: le quartile concerné :param quartile: le quartile concerné
:return : la position du quartile (arondis à l'entier suppérieur, non arrondis) :return : la position du quartile (arondis à l'entier suppérieur, non arrondis)
""" """
return quartile * self.effectif_total() / 4 return quartile * self.effectif_total() / 4
# -------------------------- # --------------------------
# Rendu latex # Rendu latex
def tabular_latex(self, nbr_lines = 1): def tabular_latex(self, nbr_lines = 1):
""" Latex code to display dataset as a tabular """ """ Latex code to display dataset as a tabular """
d_per_line = self.effectif_total() // nbr_lines d_per_line = self.effectif_total() // nbr_lines
@ -188,5 +188,5 @@ class Dataset(list):
# ----------------------------- # -----------------------------
# Reglages pour 'vim' # Reglages pour 'vim'
# vim:set autoindent expandtab tabstop=4 shiftwidth=4: # vim:set autoindent expandtab tabstop=4 shiftwidth=4:
# cursor: 16 del # cursor: 16 del

View File

@ -23,5 +23,5 @@ def number_factory(fun):
# ----------------------------- # -----------------------------
# Reglages pour 'vim' # Reglages pour 'vim'
# vim:set autoindent expandtab tabstop=4 shiftwidth=4: # vim:set autoindent expandtab tabstop=4 shiftwidth=4:
# cursor: 16 del # cursor: 16 del

View File

@ -70,5 +70,5 @@ def random_generator(length,\
# ----------------------------- # -----------------------------
# Reglages pour 'vim' # Reglages pour 'vim'
# vim:set autoindent expandtab tabstop=4 shiftwidth=4: # vim:set autoindent expandtab tabstop=4 shiftwidth=4:
# cursor: 16 del # cursor: 16 del

View File

@ -16,7 +16,7 @@ from .number_tools import number_factory
class WeightedDataset(dict): class WeightedDataset(dict):
""" A weighted dataset with statistics and latex rendering methods """ A weighted dataset with statistics and latex rendering methods
>>> w = WeightedDataset([1, 2, 3, 4], "Enfants", [10, 11, 12, 13]) >>> w = WeightedDataset([1, 2, 3, 4], "Enfants", [10, 11, 12, 13])
>>> print(w) >>> print(w)
{1: 10, 2: 11, 3: 12, 4: 13} {1: 10, 2: 11, 3: 12, 4: 13}
@ -32,12 +32,12 @@ class WeightedDataset(dict):
1.24 1.24
>>> w.sd() >>> w.sd()
1.11 1.11
""" """
def __init__(self, datas = [], data_name = "Valeurs", weights = [], weight_name = "Effectifs"): def __init__(self, datas = [], data_name = "Valeurs", weights = [], weight_name = "Effectifs"):
""" """
Initiate the WeightedDataset Initiate the WeightedDataset
""" """
if datas and not weights: if datas and not weights:
weightedDatas = Counter(datas) weightedDatas = Counter(datas)
@ -51,7 +51,7 @@ class WeightedDataset(dict):
self.data_name = data_name self.data_name = data_name
self.weight_name = weight_name self.weight_name = weight_name
def add_data(self, data, weight = 1): def add_data(self, data, weight = 1):
try: try:
self[data] += weight self[data] += weight
@ -72,7 +72,7 @@ class WeightedDataset(dict):
@number_factory @number_factory
def mean(self): def mean(self):
return self.sum()/self.effectif_total() return self.sum()/self.effectif_total()
@number_factory @number_factory
def deviation(self): def deviation(self):
@ -83,7 +83,7 @@ class WeightedDataset(dict):
@number_factory @number_factory
def variance(self): def variance(self):
return self.deviation()/self.effectif_total() return self.deviation()/self.effectif_total()
@number_factory @number_factory
def sd(self): def sd(self):
""" Compute the standard deviation """ """ Compute the standard deviation """
@ -141,19 +141,19 @@ class WeightedDataset(dict):
return expanded_values[ceil(position)] return expanded_values[ceil(position)]
def posi_quartile(self, quartile = 1): def posi_quartile(self, quartile = 1):
""" """
Calcul la position du quartile Calcul la position du quartile
:param quartile: le quartile concerné :param quartile: le quartile concerné
:return : la position du quartile (arondis à l'entier suppérieur, non arrondis) :return : la position du quartile (arondis à l'entier suppérieur, non arrondis)
""" """
return quartile * self.effectif_total() / 4 return quartile * self.effectif_total() / 4
# -------------------------- # --------------------------
# Rendu latex # Rendu latex
def tabular_latex(self): def tabular_latex(self):
""" Latex code to display dataset as a tabular """ """ Latex code to display dataset as a tabular """
latex = "\\begin{{tabular}}{{|c|*{{{nbr_col}}}{{c|}}}} \n".format(nbr_col = len(self.keys())) latex = "\\begin{{tabular}}{{|c|*{{{nbr_col}}}{{c|}}}} \n".format(nbr_col = len(self.keys()))
@ -176,5 +176,5 @@ class WeightedDataset(dict):
# ----------------------------- # -----------------------------
# Reglages pour 'vim' # Reglages pour 'vim'
# vim:set autoindent expandtab tabstop=4 shiftwidth=4: # vim:set autoindent expandtab tabstop=4 shiftwidth=4:
# cursor: 16 del # cursor: 16 del