azrideus-mathparse 0.2.10__tar.gz → 0.2.11__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (21) hide show
  1. {azrideus_mathparse-0.2.10 → azrideus_mathparse-0.2.11}/PKG-INFO +1 -1
  2. {azrideus_mathparse-0.2.10 → azrideus_mathparse-0.2.11}/azrideus_mathparse.egg-info/PKG-INFO +1 -1
  3. {azrideus_mathparse-0.2.10 → azrideus_mathparse-0.2.11}/mathparse/__init__.py +1 -1
  4. {azrideus_mathparse-0.2.10 → azrideus_mathparse-0.2.11}/mathparse/mathparse.py +64 -16
  5. {azrideus_mathparse-0.2.10 → azrideus_mathparse-0.2.11}/mathparse/mathwords.py +37 -1
  6. {azrideus_mathparse-0.2.10 → azrideus_mathparse-0.2.11}/tests/test_binary_operations.py +41 -0
  7. {azrideus_mathparse-0.2.10 → azrideus_mathparse-0.2.11}/tests/test_unary_operations.py +81 -0
  8. {azrideus_mathparse-0.2.10 → azrideus_mathparse-0.2.11}/LICENSE +0 -0
  9. {azrideus_mathparse-0.2.10 → azrideus_mathparse-0.2.11}/README.md +0 -0
  10. {azrideus_mathparse-0.2.10 → azrideus_mathparse-0.2.11}/azrideus_mathparse.egg-info/SOURCES.txt +0 -0
  11. {azrideus_mathparse-0.2.10 → azrideus_mathparse-0.2.11}/azrideus_mathparse.egg-info/dependency_links.txt +0 -0
  12. {azrideus_mathparse-0.2.10 → azrideus_mathparse-0.2.11}/azrideus_mathparse.egg-info/requires.txt +0 -0
  13. {azrideus_mathparse-0.2.10 → azrideus_mathparse-0.2.11}/azrideus_mathparse.egg-info/top_level.txt +0 -0
  14. {azrideus_mathparse-0.2.10 → azrideus_mathparse-0.2.11}/pyproject.toml +0 -0
  15. {azrideus_mathparse-0.2.10 → azrideus_mathparse-0.2.11}/setup.cfg +0 -0
  16. {azrideus_mathparse-0.2.10 → azrideus_mathparse-0.2.11}/tests/test_complex_statements.py +0 -0
  17. {azrideus_mathparse-0.2.10 → azrideus_mathparse-0.2.11}/tests/test_language_support.py +0 -0
  18. {azrideus_mathparse-0.2.10 → azrideus_mathparse-0.2.11}/tests/test_prefix_unary_operations.py +0 -0
  19. {azrideus_mathparse-0.2.10 → azrideus_mathparse-0.2.11}/tests/test_replace_word_tokens.py +0 -0
  20. {azrideus_mathparse-0.2.10 → azrideus_mathparse-0.2.11}/tests/test_simplified_chinese.py +0 -0
  21. {azrideus_mathparse-0.2.10 → azrideus_mathparse-0.2.11}/tests/test_utils.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: azrideus-mathparse
3
- Version: 0.2.10
3
+ Version: 0.2.11
4
4
  Summary: A fork of mathparse (https://github.com/gunthercox/mathparse) for my own usage; a library for solving mathematical equations contained in strings
5
5
  Author: Gunther Cox
6
6
  License-Expression: MIT
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: azrideus-mathparse
3
- Version: 0.2.10
3
+ Version: 0.2.11
4
4
  Summary: A fork of mathparse (https://github.com/gunthercox/mathparse) for my own usage; a library for solving mathematical equations contained in strings
5
5
  Author: Gunther Cox
6
6
  License-Expression: MIT
@@ -2,4 +2,4 @@
2
2
  mathparse is a library for solving mathematical equations contained in strings
3
3
  """
4
4
 
5
- __version__ = "0.2.10"
5
+ __version__ = "0.2.11"
@@ -87,7 +87,7 @@ def to_number(val) -> Union[int, float, str, Decimal]:
87
87
  Convert a string to an int or float if possible.
88
88
  """
89
89
  # If already a number (int, float, Decimal), return as-is
90
- if isinstance(val, (int, float, Decimal)):
90
+ if isinstance(val, (int, float, Decimal, mathwords.ArgumentList)):
91
91
  return val
92
92
 
93
93
  # Check if it's a constant and convert
@@ -492,7 +492,10 @@ def to_postfix(tokens: list) -> list:
492
492
  '%': 3,
493
493
  '+': 2,
494
494
  '-': 2,
495
- '(': 1
495
+ # Commas separate function arguments, so every other operator within
496
+ # an argument is evaluated first
497
+ ',': 1,
498
+ '(': 0
496
499
  }
497
500
 
498
501
  # Unary functions have a higher precedence than binary operators
@@ -505,7 +508,7 @@ def to_postfix(tokens: list) -> list:
505
508
  postfix = []
506
509
  opstack = []
507
510
 
508
- for token in tokens:
511
+ for index, token in enumerate(tokens):
509
512
  if is_int(token):
510
513
  postfix.append(token)
511
514
  elif is_float(token):
@@ -527,6 +530,14 @@ def to_postfix(tokens: list) -> list:
527
530
  # operators like ^ only yield to strictly higher precedence so
528
531
  # that 2^3^2 = 2^(3^2) = 512 rather than (2^3)^2 = 64).
529
532
  is_left_assoc = token not in right_associative
533
+
534
+ # A decimal point directly after a number is part of that number
535
+ # (e.g. "round 2.5" is round(2.5), not round(2) . 5), so it must
536
+ # not cause a preceding unary function to be applied early
537
+ is_decimal_part = (
538
+ token == '.' and index > 0 and tokens[index - 1] != ')'
539
+ )
540
+
530
541
  while (opstack != []) and (
531
542
  (
532
543
  opstack[-1] in precedence and token in precedence and (
@@ -537,9 +548,8 @@ def to_postfix(tokens: list) -> list:
537
548
  )
538
549
  ) or
539
550
  (
540
- is_unary(
541
- opstack[-1]
542
- ) and unary_precedence >= precedence[token]
551
+ is_unary(opstack[-1]) and not is_decimal_part and
552
+ unary_precedence >= precedence[token]
543
553
  )
544
554
  ):
545
555
  postfix.append(opstack.pop())
@@ -572,7 +582,14 @@ def evaluate_postfix(tokens: list) -> Union[int, float, str, Decimal]:
572
582
  a = stack.pop()
573
583
  # Convert token (string) to number for unary function evaluation
574
584
  a = to_number(a)
575
- total = mathwords.UNARY_FUNCTIONS[token](a)
585
+ function = mathwords.UNARY_FUNCTIONS[token]
586
+ if isinstance(a, mathwords.ArgumentList) and not getattr(
587
+ function, 'variadic', False
588
+ ):
589
+ raise PostfixTokenEvaluationException(
590
+ 'Function "{}" takes a single argument'.format(token)
591
+ )
592
+ total = function(a)
576
593
  elif len(stack) == 1:
577
594
  raise PostfixTokenEvaluationException(
578
595
  'Insufficient values in expression for operator "{}"'.format(
@@ -583,7 +600,24 @@ def evaluate_postfix(tokens: list) -> Union[int, float, str, Decimal]:
583
600
  b = stack.pop()
584
601
  a = stack.pop()
585
602
 
586
- if token == '+':
603
+ if token != ',' and (
604
+ isinstance(a, mathwords.ArgumentList) or
605
+ isinstance(b, mathwords.ArgumentList)
606
+ ):
607
+ raise PostfixTokenEvaluationException(
608
+ 'Comma separated values can only be used as function '
609
+ 'arguments, such as max(3, 7)'
610
+ )
611
+
612
+ if token == ',':
613
+ # Collect comma separated function arguments into a list
614
+ # Example: 3 , 7 , 5 = [3, 7, 5]
615
+ if isinstance(a, mathwords.ArgumentList):
616
+ total = a
617
+ else:
618
+ total = mathwords.ArgumentList([to_number(a)])
619
+ total.append(to_number(b))
620
+ elif token == '+':
587
621
  total = to_number(a) + to_number(b)
588
622
  elif token == '-':
589
623
  total = to_number(a) - to_number(b)
@@ -592,12 +626,17 @@ def evaluate_postfix(tokens: list) -> Union[int, float, str, Decimal]:
592
626
  elif token == '^':
593
627
  total = to_number(a) ** to_number(b)
594
628
  elif token == '/':
595
- if Decimal(str(b)) == 0:
629
+ # Convert tokens such as constants (e.g. "pi") to numbers
630
+ # before passing them to Decimal
631
+ if to_number(b) == 0:
596
632
  total = 'undefined'
597
633
  else:
598
- total = Decimal(str(a)) / Decimal(str(b))
634
+ total = (
635
+ Decimal(str(to_number(a))) /
636
+ Decimal(str(to_number(b)))
637
+ )
599
638
  elif token == '%':
600
- if Decimal(str(b)) == 0:
639
+ if to_number(b) == 0:
601
640
  total = 'undefined'
602
641
  else:
603
642
  total = to_number(a) % to_number(b)
@@ -648,12 +687,16 @@ def evaluate_postfix(tokens: list) -> Union[int, float, str, Decimal]:
648
687
 
649
688
  result = stack.pop()
650
689
 
651
- # Convert final result from string to number if needed
690
+ if isinstance(result, mathwords.ArgumentList):
691
+ raise PostfixTokenEvaluationException(
692
+ 'Comma separated values can only be used as function arguments, '
693
+ 'such as max(3, 7)'
694
+ )
695
+
696
+ # Convert final result from string (such as "4" or a constant like "pi")
697
+ # to a number if needed
652
698
  if isinstance(result, str):
653
- if is_int(result):
654
- result = int(result)
655
- elif is_float(result):
656
- result = float(result)
699
+ result = to_number(result)
657
700
 
658
701
  return result
659
702
 
@@ -727,6 +770,11 @@ def tokenize(string: str, language: str = None, escape: str = '___') -> list:
727
770
  # Only add spaces around minus when preceded by a digit or closing
728
771
  # parenthesis
729
772
  string = re.sub(r'([\d)])\s*-\s*', r'\1 - ', string)
773
+ # Separate a leading minus from a following constant or function
774
+ # name (e.g. "-pi" or "-cos 0") so that it becomes a unary minus.
775
+ # A minus directly after a word character (as in "twenty-one") is
776
+ # left alone.
777
+ string = re.sub(r'(?<![\w.])-(?=[^\W\d_])', '- ', string)
730
778
  else:
731
779
  string = string.replace(operator, f' {operator} ')
732
780
 
@@ -2,9 +2,12 @@
2
2
  Utility methods for getting math word terms.
3
3
  """
4
4
  import math
5
+ from decimal import Decimal, ROUND_HALF_UP
5
6
 
6
7
  BINARY_OPERATORS = {
7
- '^', '*', '/', '%', '+', '-', '.'
8
+ '^', '*', '/', '%', '+', '-', '.',
9
+ # Separates the arguments of functions such as max(3, 7)
10
+ ','
8
11
  }
9
12
 
10
13
  # Each key is an ISO 639-2 language code
@@ -1676,6 +1679,30 @@ CONSTANTS = {
1676
1679
  }
1677
1680
 
1678
1681
 
1682
+ class ArgumentList(list):
1683
+ """
1684
+ The comma separated arguments of a function call, such as the "3, 7" in
1685
+ "max(3, 7)". Created by evaluating the ',' binary operator.
1686
+ """
1687
+ pass
1688
+
1689
+
1690
+ def variadic(function):
1691
+ """
1692
+ Wrap a function that takes an iterable of values (such as min or max) so
1693
+ that it can be called with either an ArgumentList or a single value.
1694
+ """
1695
+ def wrapper(x):
1696
+ if isinstance(x, ArgumentList):
1697
+ return function(x)
1698
+ return function([x])
1699
+
1700
+ # Marks the function as accepting an ArgumentList
1701
+ wrapper.variadic = True
1702
+
1703
+ return wrapper
1704
+
1705
+
1679
1706
  UNARY_FUNCTIONS = {
1680
1707
  # Roots
1681
1708
  'sqrt': math.sqrt,
@@ -1728,6 +1755,15 @@ UNARY_FUNCTIONS = {
1728
1755
  'ceil': math.ceil,
1729
1756
  'floor': math.floor,
1730
1757
  'trunc': math.trunc,
1758
+ # Round halves away from zero (2.5 -> 3, -2.5 -> -3) as is commonly
1759
+ # expected, rather than Python's round half to even (2.5 -> 2)
1760
+ 'round': lambda x: int(
1761
+ Decimal(str(x)).quantize(Decimal('1'), rounding=ROUND_HALF_UP)
1762
+ ),
1763
+
1764
+ # Functions of one or more comma separated arguments
1765
+ 'min': variadic(min),
1766
+ 'max': variadic(max),
1731
1767
 
1732
1768
  # Special functions
1733
1769
  'factorial': math.factorial,
@@ -255,3 +255,44 @@ class DoubleStarPowerTestCase(TestCase):
255
255
 
256
256
  def test_power_with_parenthesis(self):
257
257
  self.assertEqual(mathparse.parse('(10 % 4) ** 2'), 4)
258
+
259
+
260
+ class ConstantDivisionTestCase(TestCase):
261
+
262
+ def test_constant_numerator(self):
263
+ result = mathparse.parse('pi / 2')
264
+ self.assertAlmostEqual(float(result), mathwords.CONSTANTS['pi'] / 2)
265
+
266
+ def test_constant_denominator(self):
267
+ result = mathparse.parse('2 / pi')
268
+ self.assertAlmostEqual(float(result), 2 / mathwords.CONSTANTS['pi'])
269
+
270
+ def test_constant_modulo(self):
271
+ result = mathparse.parse('10 % pi')
272
+ self.assertAlmostEqual(float(result), 10 % mathwords.CONSTANTS['pi'])
273
+
274
+
275
+ class ConstantResultTestCase(TestCase):
276
+
277
+ def test_pi(self):
278
+ self.assertEqual(mathparse.parse('pi'), mathwords.CONSTANTS['pi'])
279
+
280
+ def test_e(self):
281
+ self.assertEqual(mathparse.parse('e'), mathwords.CONSTANTS['e'])
282
+
283
+ def test_constant_in_parenthesis(self):
284
+ self.assertEqual(mathparse.parse('(pi)'), mathwords.CONSTANTS['pi'])
285
+
286
+ def test_negative_constant(self):
287
+ self.assertEqual(mathparse.parse('-pi'), -mathwords.CONSTANTS['pi'])
288
+
289
+ def test_negative_constant_after_operator(self):
290
+ result = mathparse.parse('2 * -pi')
291
+ self.assertEqual(result, -2 * mathwords.CONSTANTS['pi'])
292
+
293
+ def test_negative_function(self):
294
+ self.assertEqual(mathparse.parse('-sqrt 4'), -2.0)
295
+
296
+ def test_hyphenated_number_word_is_unaffected(self):
297
+ result = mathparse.parse('twenty-one plus one', language='ENG')
298
+ self.assertEqual(result, 22)
@@ -221,3 +221,84 @@ class MathModuleUnaryFunctionTestCase(TestCase):
221
221
  self.assertAlmostEqual(
222
222
  float(mathparse.parse('degrees(pi)')), 180.0, places=3
223
223
  )
224
+
225
+ def test_sin_of_constant_division(self):
226
+ self.assertAlmostEqual(float(mathparse.parse('sin(pi/2)')), 1.0)
227
+
228
+ def test_round_half_away_from_zero(self):
229
+ self.assertEqual(mathparse.parse('round(2.5)'), 3)
230
+
231
+ def test_round_down(self):
232
+ self.assertEqual(mathparse.parse('round(2.4)'), 2)
233
+
234
+ def test_round_negative_half(self):
235
+ self.assertEqual(mathparse.parse('round(-2.5)'), -3)
236
+
237
+ def test_round_division_result(self):
238
+ self.assertEqual(mathparse.parse('round(7 / 2)'), 4)
239
+
240
+
241
+ class UnaryFunctionDecimalArgumentTestCase(TestCase):
242
+ """
243
+ A decimal number directly after a unary function is its whole argument.
244
+ """
245
+
246
+ def test_round_without_parenthesis(self):
247
+ self.assertEqual(mathparse.parse('round 2.5'), 3)
248
+
249
+ def test_floor(self):
250
+ self.assertEqual(mathparse.parse('floor 3.7'), 3)
251
+
252
+ def test_sqrt(self):
253
+ self.assertEqual(mathparse.parse('sqrt 2.25'), 1.5)
254
+
255
+ def test_sqrt_then_addition(self):
256
+ self.assertEqual(mathparse.parse('sqrt 2.25 + 1'), 2.5)
257
+
258
+ def test_unary_function_binds_tighter_than_power(self):
259
+ self.assertEqual(mathparse.parse('sqrt 2.25 ^ 2'), 2.25)
260
+
261
+ def test_ceil_then_multiplication(self):
262
+ self.assertEqual(mathparse.parse('ceil 1.2 * 2'), 4)
263
+
264
+
265
+ class MinMaxFunctionTestCase(TestCase):
266
+
267
+ def test_max_plus_min(self):
268
+ self.assertEqual(mathparse.parse('max(3, 7) + min(2, 5)'), 9)
269
+
270
+ def test_without_spaces(self):
271
+ self.assertEqual(mathparse.parse('max(3,7)'), 7)
272
+
273
+ def test_more_than_two_arguments(self):
274
+ self.assertEqual(mathparse.parse('min(4, 1, 9, 2)'), 1)
275
+
276
+ def test_single_argument(self):
277
+ self.assertEqual(mathparse.parse('max(5)'), 5)
278
+
279
+ def test_expression_arguments(self):
280
+ self.assertEqual(mathparse.parse('max(1 + 2, 3 * 4)'), 12)
281
+
282
+ def test_nested(self):
283
+ self.assertEqual(mathparse.parse('max(min(1, 2), 3)'), 3)
284
+
285
+ def test_negative_arguments(self):
286
+ self.assertEqual(mathparse.parse('max(-3, -7)'), -3)
287
+
288
+ def test_decimal_arguments(self):
289
+ self.assertEqual(mathparse.parse('max(1.5, 1.25)'), 1.5)
290
+
291
+ def test_in_expression(self):
292
+ self.assertEqual(mathparse.parse('2 * max(sqrt 16, 2.5) ^ 2'), 32.0)
293
+
294
+ def test_with_words(self):
295
+ result = mathparse.parse('max(three, seven) plus one', language='ENG')
296
+ self.assertEqual(result, 8)
297
+
298
+ def test_single_argument_function_with_arguments(self):
299
+ with self.assertRaises(mathparse.PostfixTokenEvaluationException):
300
+ mathparse.parse('sin(1, 2)')
301
+
302
+ def test_arguments_outside_function(self):
303
+ with self.assertRaises(mathparse.PostfixTokenEvaluationException):
304
+ mathparse.parse('2 + (1, 2)')