@@ -59,31 +59,22 @@ def __init__(self, expression, func=None):
5959 :param expression: mathematical expression as string
6060 """
6161 # Validate on expression and raise exception if not true
62-
63- # if " " in expression:
64- # raise ExpressionFormatException("Expression should not de with spaces")
65-
66- # expression = expression.replace(" ", "")
67-
6862 if not expression :
6963 raise NoExpressionException ("The expression was not passed" )
7064
71- # if expression.startswith("--") or expression.startswith("=") or expression.startswith("+"):
72- # raise ExpressionFormatException("The expression bad format")
73- # if expression.endswith("-"):
74- # raise ExpressionFormatException("The expression bad format")
75-
76- # TODO: comment
65+ # Validate function and constant function in expression
7766 self ._mathematical_functions = {
7867 name : val for name , val in getmembers (math ) if type (val ).__name__ == "builtin_function_or_method"
7968 }
8069 self ._mathematical_functions ["abs" ] = abs
8170 self ._mathematical_functions ["round" ] = round
8271
72+ # Validate mathematical constants in expression
8373 self ._mathematical_constants = {
8474 name : val for name , val in getmembers (math ) if type (val ).__name__ == "float"
8575 }
8676
77+ # Check function in expression
8778 self ._func = None
8879 if func :
8980 func = func .strip ()
@@ -158,12 +149,14 @@ def __init__(self, expression, func=None):
158149 bracket_closed = False
159150
160151 # Validate and count brackets
152+
161153 if i == "(" :
162154 bracket_level += 1
163155 if bracket_level == 1 :
164156 continue
165157
166158 # Validate and sorted data in brackets
159+
167160 elif i == ")" :
168161 bracket_level -= 1
169162 bracket_closed = True
@@ -190,7 +183,10 @@ def __init__(self, expression, func=None):
190183 if item :
191184 if item in self ._mathematical_constants :
192185 item = self ._mathematical_constants [item ]
193- self ._expression .append (float (item ))
186+ try :
187+ self ._expression .append (float (item ))
188+ except ValueError :
189+ raise ExpressionFormatException ("Could not convert string to float: '{}'" .format (item ))
194190 item = []
195191
196192 # Handle double mathematical operation
@@ -216,6 +212,7 @@ def __init__(self, expression, func=None):
216212 except ValueError :
217213 raise ExpressionFormatException ("Could not convert string to float: '{}'" .format (item ))
218214
215+ # Conversation to string expression
219216 def __str__ (self ):
220217 """
221218 String representation of the class
@@ -229,6 +226,7 @@ def __str__(self):
229226 data = ", " .join (result )
230227 )
231228
229+ # Calculate comparison expression
232230 def _calculate_boolean_expression (self ):
233231 boolean_value = True
234232 for i , v in enumerate (self ._expression ):
@@ -260,6 +258,7 @@ def _calculate_boolean_expression(self):
260258 return boolean_value
261259 return boolean_value
262260
261+ # Calculate mathematical expression
263262 def _calculate_mathematical_expression (self ):
264263 operation = None
265264 first_negative = False
@@ -275,8 +274,6 @@ def _calculate_mathematical_expression(self):
275274 if el == "^" :
276275 self ._expression .pop (i )
277276 power = self ._expression .pop (i )
278- if power == "-" :
279- power = - self ._expression .pop (i )
280277 self ._expression [i - 1 ] **= power
281278 i -= 1
282279
@@ -313,8 +310,6 @@ def _calculate_mathematical_expression(self):
313310 if isinstance (i , str ):
314311 if i in ("+" , "-" ,):
315312 operation = i
316- # else:
317- # raise UnsupportedMathematicalOperationException("We do not support '{}' operation".format(i))
318313 elif operation :
319314 if operation == "+" :
320315 value += i
@@ -330,23 +325,13 @@ def _calculate_mathematical_expression(self):
330325
331326 return value
332327
328+ # Calculate value expression
333329 def value (self ):
334330 """
335331 Method for expression calculation
336332 :return: calculate value
337333 """
338-
339- # Validate mathematical operations and calculate nested expressions
340- # i = len(self._expression) - 1
341- # last_operation = None
342- # print(">>", self._expression)
343- # while i >= 0:
344- # el = self._expression[i]
345- # if isinstance(el, Element):
346- # self._expression[i] = el.value()
347- # last_operation = None
348- # elif isinstance(el, str):
349-
334+ # Validate unary operation
350335 for i , v in enumerate (self ._expression ):
351336 if isinstance (v , Element ):
352337 self ._expression [i ] = v .value ()
@@ -360,9 +345,11 @@ def value(self):
360345 if v .startswith ("+" ):
361346 self ._expression [i ] = "+"
362347
348+ # Validate negative item in expression
363349 expression = []
364350 last_operation = None
365351 sign = None
352+
366353 for i , v in enumerate (self ._expression ):
367354 if isinstance (v , str ):
368355 if last_operation :
@@ -399,33 +386,14 @@ def value(self):
399386 last_operation = None
400387 if sign == "-" :
401388 v = - v
402- sign = None
389+ sign = None
403390 expression .append (v )
404391
405392 if last_operation or sign :
406393 raise ExpressionFormatException ("Expression finishes with mathematical operation." )
407394
408395 self ._expression = expression
409396
410- # for i, v in enumerate(self._expression):
411- # if isinstance(v, str):
412- # if last_operation and v in ("+", "-",):
413- # if last_operation == "+" and v == "-":
414- # self._expression[i] = "-"
415- # elif last_operation == "-" and v == "+":
416- # self._expression[i] = "-"
417- # del self._expression[i - 1]
418- # elif last_operation and v in self.MATH_ACTIONS:
419- # raise DoubleOperationException("'{so}' operation follows '{fo}'".format(
420- # so=last_operation,
421- # fo=v
422- # ))
423-
424- # if v in self.MATH_ACTIONS:
425- # last_operation = v
426- # else:
427- # last_operation = None
428-
429397 # Evaluate comparison expression
430398 if self ._comparison_operation :
431399 return self ._calculate_boolean_expression ()
@@ -436,6 +404,5 @@ def value(self):
436404 return self ._func (* self ._expression )
437405 except TypeError :
438406 raise ExpressionFormatException ("Expected 2 arguments: '{}'" .format (self ._func ))
439-
440- # print(self._expression)
407+ # Value mathematical expression
441408 return self ._calculate_mathematical_expression ()
0 commit comments