azrideus-mathparse 0.2.9__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 (22) hide show
  1. {azrideus_mathparse-0.2.9 → azrideus_mathparse-0.2.11}/PKG-INFO +1 -1
  2. {azrideus_mathparse-0.2.9 → azrideus_mathparse-0.2.11}/azrideus_mathparse.egg-info/PKG-INFO +1 -1
  3. {azrideus_mathparse-0.2.9 → azrideus_mathparse-0.2.11}/mathparse/__init__.py +1 -1
  4. {azrideus_mathparse-0.2.9 → azrideus_mathparse-0.2.11}/mathparse/mathparse.py +97 -16
  5. {azrideus_mathparse-0.2.9 → azrideus_mathparse-0.2.11}/mathparse/mathwords.py +1815 -1777
  6. azrideus_mathparse-0.2.11/tests/test_binary_operations.py +298 -0
  7. {azrideus_mathparse-0.2.9 → azrideus_mathparse-0.2.11}/tests/test_unary_operations.py +86 -3
  8. azrideus_mathparse-0.2.9/tests/test_binary_operations.py +0 -174
  9. {azrideus_mathparse-0.2.9 → azrideus_mathparse-0.2.11}/LICENSE +0 -0
  10. {azrideus_mathparse-0.2.9 → azrideus_mathparse-0.2.11}/README.md +0 -0
  11. {azrideus_mathparse-0.2.9 → azrideus_mathparse-0.2.11}/azrideus_mathparse.egg-info/SOURCES.txt +0 -0
  12. {azrideus_mathparse-0.2.9 → azrideus_mathparse-0.2.11}/azrideus_mathparse.egg-info/dependency_links.txt +0 -0
  13. {azrideus_mathparse-0.2.9 → azrideus_mathparse-0.2.11}/azrideus_mathparse.egg-info/requires.txt +0 -0
  14. {azrideus_mathparse-0.2.9 → azrideus_mathparse-0.2.11}/azrideus_mathparse.egg-info/top_level.txt +0 -0
  15. {azrideus_mathparse-0.2.9 → azrideus_mathparse-0.2.11}/pyproject.toml +0 -0
  16. {azrideus_mathparse-0.2.9 → azrideus_mathparse-0.2.11}/setup.cfg +0 -0
  17. {azrideus_mathparse-0.2.9 → azrideus_mathparse-0.2.11}/tests/test_complex_statements.py +0 -0
  18. {azrideus_mathparse-0.2.9 → azrideus_mathparse-0.2.11}/tests/test_language_support.py +0 -0
  19. {azrideus_mathparse-0.2.9 → azrideus_mathparse-0.2.11}/tests/test_prefix_unary_operations.py +0 -0
  20. {azrideus_mathparse-0.2.9 → azrideus_mathparse-0.2.11}/tests/test_replace_word_tokens.py +0 -0
  21. {azrideus_mathparse-0.2.9 → azrideus_mathparse-0.2.11}/tests/test_simplified_chinese.py +0 -0
  22. {azrideus_mathparse-0.2.9 → 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.9
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.9
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.9'
5
+ __version__ = "0.2.11"
@@ -33,7 +33,8 @@ def is_float(string: str) -> bool:
33
33
  """
34
34
  try:
35
35
  float(string)
36
- return '.' in string
36
+ # Exponent format numbers such as "25e2" are also floats
37
+ return '.' in string or 'e' in string
37
38
  except ValueError:
38
39
  return False
39
40
 
@@ -86,7 +87,7 @@ def to_number(val) -> Union[int, float, str, Decimal]:
86
87
  Convert a string to an int or float if possible.
87
88
  """
88
89
  # If already a number (int, float, Decimal), return as-is
89
- if isinstance(val, (int, float, Decimal)):
90
+ if isinstance(val, (int, float, Decimal, mathwords.ArgumentList)):
90
91
  return val
91
92
 
92
93
  # Check if it's a constant and convert
@@ -102,6 +103,25 @@ def to_number(val) -> Union[int, float, str, Decimal]:
102
103
  return val
103
104
 
104
105
 
106
+ # Numbers in exponent format, such as "2.5e3", "1e-6" or ".5E+2"
107
+ SCIENTIFIC_NOTATION_PATTERN = re.compile(
108
+ r'(?<![\w.])(\d+\.?\d*|\.\d+)e([+-]?\d+)(?![\w.])'
109
+ )
110
+
111
+
112
+ def normalize_scientific_notation(string: str) -> str:
113
+ """
114
+ Rewrite exponent format numbers without decimal points or plus signs so
115
+ that they are kept as a single token, rather than being split apart by the
116
+ '.' and '+' binary operators. For example "2.5e+3" becomes "25e2".
117
+ """
118
+ def replace(match):
119
+ _, digits, exponent = Decimal(match.group(0)).as_tuple()
120
+ return '{}e{}'.format(''.join(str(d) for d in digits), exponent)
121
+
122
+ return SCIENTIFIC_NOTATION_PATTERN.sub(replace, string)
123
+
124
+
105
125
  def create_unicode_word_boundary_pattern(word: str) -> str:
106
126
  """
107
127
  Create a regex pattern with Unicode-aware word boundaries.
@@ -469,9 +489,13 @@ def to_postfix(tokens: list) -> list:
469
489
  '^': 4,
470
490
  '/': 3,
471
491
  '*': 3,
492
+ '%': 3,
472
493
  '+': 2,
473
494
  '-': 2,
474
- '(': 1
495
+ # Commas separate function arguments, so every other operator within
496
+ # an argument is evaluated first
497
+ ',': 1,
498
+ '(': 0
475
499
  }
476
500
 
477
501
  # Unary functions have a higher precedence than binary operators
@@ -484,7 +508,7 @@ def to_postfix(tokens: list) -> list:
484
508
  postfix = []
485
509
  opstack = []
486
510
 
487
- for token in tokens:
511
+ for index, token in enumerate(tokens):
488
512
  if is_int(token):
489
513
  postfix.append(token)
490
514
  elif is_float(token):
@@ -506,6 +530,14 @@ def to_postfix(tokens: list) -> list:
506
530
  # operators like ^ only yield to strictly higher precedence so
507
531
  # that 2^3^2 = 2^(3^2) = 512 rather than (2^3)^2 = 64).
508
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
+
509
541
  while (opstack != []) and (
510
542
  (
511
543
  opstack[-1] in precedence and token in precedence and (
@@ -516,9 +548,8 @@ def to_postfix(tokens: list) -> list:
516
548
  )
517
549
  ) or
518
550
  (
519
- is_unary(
520
- opstack[-1]
521
- ) and unary_precedence >= precedence[token]
551
+ is_unary(opstack[-1]) and not is_decimal_part and
552
+ unary_precedence >= precedence[token]
522
553
  )
523
554
  ):
524
555
  postfix.append(opstack.pop())
@@ -551,7 +582,14 @@ def evaluate_postfix(tokens: list) -> Union[int, float, str, Decimal]:
551
582
  a = stack.pop()
552
583
  # Convert token (string) to number for unary function evaluation
553
584
  a = to_number(a)
554
- 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)
555
593
  elif len(stack) == 1:
556
594
  raise PostfixTokenEvaluationException(
557
595
  'Insufficient values in expression for operator "{}"'.format(
@@ -562,7 +600,24 @@ def evaluate_postfix(tokens: list) -> Union[int, float, str, Decimal]:
562
600
  b = stack.pop()
563
601
  a = stack.pop()
564
602
 
565
- 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 == '+':
566
621
  total = to_number(a) + to_number(b)
567
622
  elif token == '-':
568
623
  total = to_number(a) - to_number(b)
@@ -571,10 +626,20 @@ def evaluate_postfix(tokens: list) -> Union[int, float, str, Decimal]:
571
626
  elif token == '^':
572
627
  total = to_number(a) ** to_number(b)
573
628
  elif token == '/':
574
- 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:
632
+ total = 'undefined'
633
+ else:
634
+ total = (
635
+ Decimal(str(to_number(a))) /
636
+ Decimal(str(to_number(b)))
637
+ )
638
+ elif token == '%':
639
+ if to_number(b) == 0:
575
640
  total = 'undefined'
576
641
  else:
577
- total = Decimal(str(a)) / Decimal(str(b))
642
+ total = to_number(a) % to_number(b)
578
643
  elif token == '.':
579
644
  # Treat decimal points as a binary operator that combines the
580
645
  # integer and fractional part of two numbers
@@ -622,12 +687,16 @@ def evaluate_postfix(tokens: list) -> Union[int, float, str, Decimal]:
622
687
 
623
688
  result = stack.pop()
624
689
 
625
- # 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
626
698
  if isinstance(result, str):
627
- if is_int(result):
628
- result = int(result)
629
- elif is_float(result):
630
- result = float(result)
699
+ result = to_number(result)
631
700
 
632
701
  return result
633
702
 
@@ -653,6 +722,9 @@ def tokenize(string: str, language: str = None, escape: str = '___') -> list:
653
722
  # Set all words to lowercase
654
723
  string = string.lower()
655
724
 
725
+ # Keep exponent format numbers (e.g. 2.5e3) together as single tokens
726
+ string = normalize_scientific_notation(string)
727
+
656
728
  # Ignore punctuation
657
729
  if len(string) and not string[-1].isalnum():
658
730
  character = string[-1]
@@ -679,6 +751,10 @@ def tokenize(string: str, language: str = None, escape: str = '___') -> list:
679
751
  # Replace spaced version with non-spaced version
680
752
  string = string.replace(spaced_phrase, phrase)
681
753
 
754
+ # Python style power operator is an alias for '^'. This must be replaced
755
+ # before '*' is split apart as a binary operator below.
756
+ string = string.replace('**', '^')
757
+
682
758
  # Binary operators must have space around them to be tokenized properly
683
759
  # Special handling for minus sign: preserve leading negatives
684
760
  for operator in mathwords.BINARY_OPERATORS:
@@ -694,6 +770,11 @@ def tokenize(string: str, language: str = None, escape: str = '___') -> list:
694
770
  # Only add spaces around minus when preceded by a digit or closing
695
771
  # parenthesis
696
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)
697
778
  else:
698
779
  string = string.replace(operator, f' {operator} ')
699
780