azrideus-mathparse 0.2.12__tar.gz → 0.2.14__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 (25) hide show
  1. {azrideus_mathparse-0.2.12 → azrideus_mathparse-0.2.14}/PKG-INFO +1 -1
  2. {azrideus_mathparse-0.2.12 → azrideus_mathparse-0.2.14}/azrideus_mathparse.egg-info/PKG-INFO +1 -1
  3. {azrideus_mathparse-0.2.12 → azrideus_mathparse-0.2.14}/azrideus_mathparse.egg-info/SOURCES.txt +3 -0
  4. {azrideus_mathparse-0.2.12 → azrideus_mathparse-0.2.14}/mathparse/__init__.py +1 -1
  5. {azrideus_mathparse-0.2.12 → azrideus_mathparse-0.2.14}/mathparse/mathparse.py +112 -10
  6. {azrideus_mathparse-0.2.12 → azrideus_mathparse-0.2.14}/mathparse/mathwords.py +39 -2
  7. azrideus_mathparse-0.2.14/tests/test_bitshift_operations.py +101 -0
  8. azrideus_mathparse-0.2.14/tests/test_comparison_operations.py +138 -0
  9. azrideus_mathparse-0.2.14/tests/test_hex_numbers.py +94 -0
  10. {azrideus_mathparse-0.2.12 → azrideus_mathparse-0.2.14}/tests/test_limits.py +13 -18
  11. {azrideus_mathparse-0.2.12 → azrideus_mathparse-0.2.14}/LICENSE +0 -0
  12. {azrideus_mathparse-0.2.12 → azrideus_mathparse-0.2.14}/README.md +0 -0
  13. {azrideus_mathparse-0.2.12 → azrideus_mathparse-0.2.14}/azrideus_mathparse.egg-info/dependency_links.txt +0 -0
  14. {azrideus_mathparse-0.2.12 → azrideus_mathparse-0.2.14}/azrideus_mathparse.egg-info/requires.txt +0 -0
  15. {azrideus_mathparse-0.2.12 → azrideus_mathparse-0.2.14}/azrideus_mathparse.egg-info/top_level.txt +0 -0
  16. {azrideus_mathparse-0.2.12 → azrideus_mathparse-0.2.14}/pyproject.toml +0 -0
  17. {azrideus_mathparse-0.2.12 → azrideus_mathparse-0.2.14}/setup.cfg +0 -0
  18. {azrideus_mathparse-0.2.12 → azrideus_mathparse-0.2.14}/tests/test_binary_operations.py +0 -0
  19. {azrideus_mathparse-0.2.12 → azrideus_mathparse-0.2.14}/tests/test_complex_statements.py +0 -0
  20. {azrideus_mathparse-0.2.12 → azrideus_mathparse-0.2.14}/tests/test_language_support.py +0 -0
  21. {azrideus_mathparse-0.2.12 → azrideus_mathparse-0.2.14}/tests/test_prefix_unary_operations.py +0 -0
  22. {azrideus_mathparse-0.2.12 → azrideus_mathparse-0.2.14}/tests/test_replace_word_tokens.py +0 -0
  23. {azrideus_mathparse-0.2.12 → azrideus_mathparse-0.2.14}/tests/test_simplified_chinese.py +0 -0
  24. {azrideus_mathparse-0.2.12 → azrideus_mathparse-0.2.14}/tests/test_unary_operations.py +0 -0
  25. {azrideus_mathparse-0.2.12 → azrideus_mathparse-0.2.14}/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.12
3
+ Version: 0.2.14
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.12
3
+ Version: 0.2.14
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
@@ -10,7 +10,10 @@ mathparse/__init__.py
10
10
  mathparse/mathparse.py
11
11
  mathparse/mathwords.py
12
12
  tests/test_binary_operations.py
13
+ tests/test_bitshift_operations.py
14
+ tests/test_comparison_operations.py
13
15
  tests/test_complex_statements.py
16
+ tests/test_hex_numbers.py
14
17
  tests/test_language_support.py
15
18
  tests/test_limits.py
16
19
  tests/test_prefix_unary_operations.py
@@ -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.12"
5
+ __version__ = "0.2.14"
@@ -77,6 +77,14 @@ def is_float(string: str) -> bool:
77
77
  return False
78
78
 
79
79
 
80
+ def is_hex(string: str) -> bool:
81
+ """
82
+ Return true if the string is a hexadecimal integer literal such as "0x44"
83
+ or "-0x44", which is the format produced by the hex() function.
84
+ """
85
+ return HEX_NUMBER_PATTERN.fullmatch(string.lstrip("-")) is not None
86
+
87
+
80
88
  def is_constant(string: str) -> bool:
81
89
  """
82
90
  Return true if the string is a mathematical constant.
@@ -140,6 +148,9 @@ def to_number(val) -> Union[int, float, str, Decimal]:
140
148
  return int(val)
141
149
  elif is_float(val):
142
150
  return float(val)
151
+ elif is_hex(val):
152
+ # The result of hex(), so that it can be used in further arithmetic
153
+ return int(val, 16)
143
154
 
144
155
  return val
145
156
 
@@ -150,6 +161,24 @@ SCIENTIFIC_NOTATION_PATTERN = re.compile(
150
161
  )
151
162
 
152
163
 
164
+ # Hexadecimal integer literals such as "0x44" or "0XFF". The lookarounds stop
165
+ # the pattern from matching inside a longer word such as "10x44" or "0x44g".
166
+ HEX_NUMBER_PATTERN = re.compile(r"(?<![\w.])0x([0-9a-f]+)(?![\w.])", re.IGNORECASE)
167
+
168
+ # Two character operators must be matched before the single character ones,
169
+ # so that "<<" and "<=" are not split into "<" followed by "<" or "=".
170
+ COMPARISON_OPERATOR_PATTERN = re.compile(r"<<|>>|<=|>=|==|!=|<|>|=")
171
+
172
+ COMPARISON_FUNCTIONS = {
173
+ "<": lambda a, b: a < b,
174
+ ">": lambda a, b: a > b,
175
+ "<=": lambda a, b: a <= b,
176
+ ">=": lambda a, b: a >= b,
177
+ "==": lambda a, b: a == b,
178
+ "!=": lambda a, b: a != b,
179
+ }
180
+
181
+
153
182
  def normalize_scientific_notation(string: str) -> str:
154
183
  """
155
184
  Rewrite exponent format numbers without decimal points or plus signs so
@@ -164,6 +193,19 @@ def normalize_scientific_notation(string: str) -> str:
164
193
  return SCIENTIFIC_NOTATION_PATTERN.sub(replace, string)
165
194
 
166
195
 
196
+ def normalize_hex_numbers(string: str) -> str:
197
+ """
198
+ Rewrite hexadecimal integer literals as decimal integers so that they can
199
+ be tokenized and evaluated like any other number. For example "0x44 + 0x40"
200
+ becomes "68 + 64".
201
+ """
202
+
203
+ def replace(match):
204
+ return str(int(match.group(1), 16))
205
+
206
+ return HEX_NUMBER_PATTERN.sub(replace, string)
207
+
208
+
167
209
  def create_unicode_word_boundary_pattern(word: str) -> str:
168
210
  """
169
211
  Create a regex pattern with Unicode-aware word boundaries.
@@ -517,13 +559,25 @@ def to_postfix(tokens: list) -> list:
517
559
  Convert a list of evaluatable tokens to postfix format.
518
560
  """
519
561
  precedence = {
520
- ".": 5,
521
- "^": 4,
522
- "/": 3,
523
- "*": 3,
524
- "%": 3,
525
- "+": 2,
526
- "-": 2,
562
+ ".": 7,
563
+ "^": 6,
564
+ "/": 5,
565
+ "*": 5,
566
+ "%": 5,
567
+ "+": 4,
568
+ "-": 4,
569
+ # Bit shifts are evaluated after arithmetic, as in Python, so that
570
+ # 1 + 2 << 1 is (1 + 2) << 1
571
+ "<<": 3,
572
+ ">>": 3,
573
+ # Comparisons are evaluated after arithmetic and shifts, so that
574
+ # 1 + 2 <= 4 is (1 + 2) <= 4
575
+ "<": 2,
576
+ ">": 2,
577
+ "<=": 2,
578
+ ">=": 2,
579
+ "==": 2,
580
+ "!=": 2,
527
581
  # Commas separate function arguments, so every other operator within
528
582
  # an argument is evaluated first
529
583
  ",": 1,
@@ -686,6 +740,35 @@ def evaluate_postfix(tokens: list) -> Union[int, float, str, Decimal]:
686
740
  total = "undefined"
687
741
  else:
688
742
  total = to_number(a) % to_number(b)
743
+ elif token in mathwords.COMPARISON_OPERATORS:
744
+ total = COMPARISON_FUNCTIONS[token](to_number(a), to_number(b))
745
+ elif token in mathwords.SHIFT_OPERATORS:
746
+ value = to_number(a)
747
+ count = to_number(b)
748
+ # Bit shifts are only defined for integers (True and False
749
+ # count as 1 and 0)
750
+ if not isinstance(value, int) or not isinstance(count, int):
751
+ raise PostfixTokenEvaluationException(
752
+ 'Bit shift operator "{}" requires integer operands'.format(
753
+ token
754
+ )
755
+ )
756
+ if count < 0:
757
+ raise PostfixTokenEvaluationException(
758
+ 'Bit shift operator "{}" requires a non-negative shift '
759
+ "count".format(token)
760
+ )
761
+ if token == "<<":
762
+ # Check the size of the result before computing it, since
763
+ # a huge shift (e.g. 1 << 999999999) would use all
764
+ # available memory. Each shift multiplies the value by 2.
765
+ if value != 0:
766
+ check_integer_digits(
767
+ math.log10(abs(value)) + count * math.log10(2), token
768
+ )
769
+ total = value << count
770
+ else:
771
+ total = value >> count
689
772
  elif token == ".":
690
773
  # Treat decimal points as a binary operator that combines the
691
774
  # integer and fractional part of two numbers
@@ -746,8 +829,9 @@ def evaluate_postfix(tokens: list) -> Union[int, float, str, Decimal]:
746
829
  )
747
830
 
748
831
  # Convert final result from string (such as "4" or a constant like "pi")
749
- # to a number if needed
750
- if isinstance(result, str):
832
+ # to a number if needed. A hexadecimal string produced by hex() is kept
833
+ # as-is, since that is the requested output format.
834
+ if isinstance(result, str) and not is_hex(result):
751
835
  result = to_number(result)
752
836
 
753
837
  return result
@@ -774,6 +858,10 @@ def tokenize(string: str, language: str = None, escape: str = "___") -> list:
774
858
  # Set all words to lowercase
775
859
  string = string.lower()
776
860
 
861
+ # Convert hexadecimal literals (e.g. 0x44) to decimal integers. This must
862
+ # happen before the exponent format check so that "0x1e3" is read as hex.
863
+ string = normalize_hex_numbers(string)
864
+
777
865
  # Keep exponent format numbers (e.g. 2.5e3) together as single tokens
778
866
  string = normalize_scientific_notation(string)
779
867
 
@@ -807,9 +895,21 @@ def tokenize(string: str, language: str = None, escape: str = "___") -> list:
807
895
  # before '*' is split apart as a binary operator below.
808
896
  string = string.replace("**", "^")
809
897
 
898
+ # Comparison and bit shift operators are spaced out in one pass, longest
899
+ # first, so that "<=" and "<<" are kept together rather than split into
900
+ # "<" and "=" or "<" and "<". A single "=" is an alias for "==".
901
+ string = COMPARISON_OPERATOR_PATTERN.sub(
902
+ lambda match: " {} ".format("==" if match.group() == "=" else match.group()),
903
+ string,
904
+ )
905
+
810
906
  # Binary operators must have space around them to be tokenized properly
811
907
  # Special handling for minus sign: preserve leading negatives
812
- for operator in mathwords.BINARY_OPERATORS:
908
+ for operator in (
909
+ mathwords.BINARY_OPERATORS
910
+ - mathwords.COMPARISON_OPERATORS
911
+ - mathwords.SHIFT_OPERATORS
912
+ ):
813
913
  if operator == "-":
814
914
  # For minus sign, use a pattern that only spaces it when it's
815
915
  # clearly a binary operator (after digits or closing parenthesis).
@@ -907,6 +1007,8 @@ def parse(
907
1007
  - Follows standard order of operations (PEMDAS)
908
1008
  - Supports mathematical constants: pi, e
909
1009
  - Supports unary functions: sqrt, log
1010
+ - Supports comparison operators (<, >, <=, >=, ==, !=), which
1011
+ evaluate to True or False after any arithmetic on either side
910
1012
  - Each expression must use terms from a single language
911
1013
  - Division by zero returns 'undefined' instead of raising an exception
912
1014
  - Raises ExpressionTooLargeException if the expression is longer than
@@ -4,11 +4,17 @@ Utility methods for getting math word terms.
4
4
  import math
5
5
  from decimal import Decimal, ROUND_HALF_UP
6
6
 
7
+ # Comparison operators evaluate to True or False
8
+ COMPARISON_OPERATORS = {'<', '>', '<=', '>=', '==', '!='}
9
+
10
+ # Bit shift operators move the bits of an integer left or right
11
+ SHIFT_OPERATORS = {'<<', '>>'}
12
+
7
13
  BINARY_OPERATORS = {
8
14
  '^', '*', '/', '%', '+', '-', '.',
9
15
  # Separates the arguments of functions such as max(3, 7)
10
16
  ','
11
- }
17
+ } | COMPARISON_OPERATORS | SHIFT_OPERATORS
12
18
 
13
19
  # Each key is an ISO 639-2 language code
14
20
  # https://www.loc.gov/standards/iso639-2/php/code_list.php
@@ -88,7 +94,20 @@ MATH_WORDS = {
88
94
  'to the power of': '^',
89
95
  'modulo': '%',
90
96
  'mod': '%',
91
- 'point': '.'
97
+ 'shifted left by': '<<',
98
+ 'shift left by': '<<',
99
+ 'left shift': '<<',
100
+ 'shifted right by': '>>',
101
+ 'shift right by': '>>',
102
+ 'right shift': '>>',
103
+ 'point': '.',
104
+ 'greater than or equal to': '>=',
105
+ 'less than or equal to': '<=',
106
+ 'greater than': '>',
107
+ 'less than': '<',
108
+ 'not equal to': '!=',
109
+ 'equal to': '==',
110
+ 'equals': '=='
92
111
  },
93
112
  'numbers': {
94
113
  'zero': 0,
@@ -1703,6 +1722,21 @@ def variadic(function):
1703
1722
  return wrapper
1704
1723
 
1705
1724
 
1725
+ def to_hex(value):
1726
+ """
1727
+ Return the hexadecimal representation of an integer value as a string,
1728
+ such as "0x5aa00". Floats and Decimals are accepted when they have no
1729
+ fractional part, for example hex(4.0) -> "0x4".
1730
+ """
1731
+ if not isinstance(value, int):
1732
+ if value != int(value):
1733
+ raise ValueError(
1734
+ 'hex() requires an integer value, got {}'.format(value)
1735
+ )
1736
+ value = int(value)
1737
+ return hex(value)
1738
+
1739
+
1706
1740
  UNARY_FUNCTIONS = {
1707
1741
  # Roots
1708
1742
  'sqrt': math.sqrt,
@@ -1765,6 +1799,9 @@ UNARY_FUNCTIONS = {
1765
1799
  'min': variadic(min),
1766
1800
  'max': variadic(max),
1767
1801
 
1802
+ # Number base conversion
1803
+ 'hex': to_hex,
1804
+
1768
1805
  # Special functions
1769
1806
  'factorial': math.factorial,
1770
1807
  'gamma': math.gamma,
@@ -0,0 +1,101 @@
1
+ from unittest import TestCase
2
+ from mathparse import mathparse
3
+
4
+
5
+ class BitShiftTestCase(TestCase):
6
+
7
+ def test_shift_left(self):
8
+ self.assertEqual(mathparse.parse("2 << 4"), 32)
9
+ self.assertEqual(mathparse.parse("1 << 0"), 1)
10
+ self.assertEqual(mathparse.parse("0 << 10"), 0)
11
+
12
+ def test_shift_right(self):
13
+ self.assertEqual(mathparse.parse("256 >> 3"), 32)
14
+ self.assertEqual(mathparse.parse("7 >> 1"), 3)
15
+ self.assertEqual(mathparse.parse("1 >> 5"), 0)
16
+
17
+ def test_without_spaces(self):
18
+ self.assertEqual(mathparse.parse("2<<4"), 32)
19
+ self.assertEqual(mathparse.parse("256>>3"), 32)
20
+
21
+ def test_tokenize_keeps_shift_operators_together(self):
22
+ self.assertEqual(mathparse.tokenize("2<<4"), ["2", "<<", "4"])
23
+ self.assertEqual(mathparse.tokenize("256 >> 3"), ["256", ">>", "3"])
24
+ self.assertEqual(mathparse.tokenize("3<=5<<1"), ["3", "<=", "5", "<<", "1"])
25
+
26
+ def test_negative_value(self):
27
+ self.assertEqual(mathparse.parse("-8 >> 1"), -4)
28
+ self.assertEqual(mathparse.parse("-1 << 3"), -8)
29
+
30
+ def test_lower_precedence_than_arithmetic(self):
31
+ # (1 + 2) << 1, not 1 + (2 << 1)
32
+ self.assertEqual(mathparse.parse("1 + 2 << 1"), 6)
33
+ self.assertEqual(mathparse.parse("1 << 2 + 1"), 8)
34
+ self.assertEqual(mathparse.parse("2 * 3 >> 1"), 3)
35
+ self.assertEqual(mathparse.parse("2 ^ 3 >> 1"), 4)
36
+ self.assertEqual(mathparse.parse("2 ** 3 >> 1"), 4)
37
+
38
+ def test_higher_precedence_than_comparison(self):
39
+ # (1 << 3) == 8, not 1 << (3 == 8)
40
+ self.assertIs(mathparse.parse("1 << 3 == 8"), True)
41
+ self.assertIs(mathparse.parse("16 >> 2 < 3"), False)
42
+
43
+ def test_parentheses(self):
44
+ self.assertEqual(mathparse.parse("(1 << 3) * 2"), 16)
45
+ self.assertEqual(mathparse.parse("1 << (1 + 2)"), 8)
46
+
47
+ def test_chained_shifts_are_left_associative(self):
48
+ # (1 << 2) << 3
49
+ self.assertEqual(mathparse.parse("1 << 2 << 3"), 32)
50
+ self.assertEqual(mathparse.parse("64 >> 2 >> 1"), 8)
51
+
52
+ def test_result_can_be_used_in_arithmetic(self):
53
+ self.assertEqual(mathparse.parse("(2 << 2) + 1"), 9)
54
+ self.assertEqual(mathparse.parse("sqrt(1 << 4)"), 4)
55
+
56
+ def test_float_operands_are_rejected(self):
57
+ with self.assertRaises(mathparse.PostfixTokenEvaluationException):
58
+ mathparse.parse("2.5 << 1")
59
+ with self.assertRaises(mathparse.PostfixTokenEvaluationException):
60
+ mathparse.parse("2 << 1.5")
61
+ with self.assertRaises(mathparse.PostfixTokenEvaluationException):
62
+ mathparse.parse("pi << 1")
63
+
64
+ def test_negative_shift_count_is_rejected(self):
65
+ with self.assertRaises(mathparse.PostfixTokenEvaluationException):
66
+ mathparse.parse("2 << -1")
67
+ with self.assertRaises(mathparse.PostfixTokenEvaluationException):
68
+ mathparse.parse("2 >> -1")
69
+
70
+ def test_missing_operand(self):
71
+ with self.assertRaises(mathparse.PostfixTokenEvaluationException):
72
+ mathparse.parse("2 <<")
73
+
74
+ def test_huge_shift_left_is_rejected(self):
75
+ with self.assertRaises(mathparse.ExpressionTooLargeException):
76
+ mathparse.parse("1 << 999999999")
77
+
78
+ def test_huge_shift_right_is_allowed(self):
79
+ self.assertEqual(mathparse.parse("1 >> 999999999"), 0)
80
+
81
+ def test_is_symbol(self):
82
+ for operator in ["<<", ">>"]:
83
+ self.assertTrue(mathparse.is_symbol(operator))
84
+ self.assertTrue(mathparse.is_binary(operator))
85
+
86
+
87
+ class BitShiftWordsTestCase(TestCase):
88
+
89
+ def test_shifted_left_by_words(self):
90
+ self.assertEqual(mathparse.parse("two shifted left by three", language="ENG"), 16)
91
+
92
+ def test_shifted_right_by_words(self):
93
+ result = mathparse.parse("sixteen shifted right by two", language="ENG")
94
+ self.assertEqual(result, 4)
95
+
96
+ def test_words_mixed_with_symbols(self):
97
+ self.assertEqual(mathparse.parse("one plus one << 2", language="ENG"), 8)
98
+
99
+ def test_extract_expression(self):
100
+ result = mathparse.extract_expression("What is 2 << 4?", language="ENG")
101
+ self.assertEqual(result, "2 << 4")
@@ -0,0 +1,138 @@
1
+ from unittest import TestCase
2
+ from mathparse import mathparse
3
+
4
+
5
+ class ComparisonTestCase(TestCase):
6
+
7
+ def test_less_than(self):
8
+ self.assertIs(mathparse.parse("3 < 5"), True)
9
+ self.assertIs(mathparse.parse("5 < 3"), False)
10
+
11
+ def test_greater_than(self):
12
+ self.assertIs(mathparse.parse("5 > 3"), True)
13
+ self.assertIs(mathparse.parse("3 > 5"), False)
14
+
15
+ def test_less_than_or_equal(self):
16
+ self.assertIs(mathparse.parse("3 <= 5"), True)
17
+ self.assertIs(mathparse.parse("5 <= 5"), True)
18
+ self.assertIs(mathparse.parse("6 <= 5"), False)
19
+
20
+ def test_greater_than_or_equal(self):
21
+ self.assertIs(mathparse.parse("5 >= 3"), True)
22
+ self.assertIs(mathparse.parse("5 >= 5"), True)
23
+ self.assertIs(mathparse.parse("4 >= 5"), False)
24
+
25
+ def test_equal(self):
26
+ self.assertIs(mathparse.parse("5 == 5"), True)
27
+ self.assertIs(mathparse.parse("5 == 4"), False)
28
+
29
+ def test_single_equals_is_alias_for_double_equals(self):
30
+ self.assertIs(mathparse.parse("2 + 2 = 4"), True)
31
+ self.assertIs(mathparse.parse("2 + 2 = 5"), False)
32
+
33
+ def test_not_equal(self):
34
+ self.assertIs(mathparse.parse("5 != 4"), True)
35
+ self.assertIs(mathparse.parse("5 != 5"), False)
36
+
37
+ def test_without_spaces(self):
38
+ self.assertIs(mathparse.parse("3<=5"), True)
39
+ self.assertIs(mathparse.parse("3>=5"), False)
40
+ self.assertIs(mathparse.parse("3==3"), True)
41
+ self.assertIs(mathparse.parse("3!=3"), False)
42
+
43
+ def test_tokenize_keeps_two_character_operators_together(self):
44
+ self.assertEqual(mathparse.tokenize("3<=5"), ["3", "<=", "5"])
45
+ self.assertEqual(mathparse.tokenize("3 >= 5"), ["3", ">=", "5"])
46
+ self.assertEqual(mathparse.tokenize("3 != 5"), ["3", "!=", "5"])
47
+ self.assertEqual(mathparse.tokenize("3 = 5"), ["3", "==", "5"])
48
+
49
+ def test_floats(self):
50
+ self.assertIs(mathparse.parse("2.5 < 2.75"), True)
51
+ self.assertIs(mathparse.parse("2.5 >= 2.75"), False)
52
+
53
+ def test_negative_numbers(self):
54
+ self.assertIs(mathparse.parse("-3 < -2"), True)
55
+ self.assertIs(mathparse.parse("3 <= -2"), False)
56
+ self.assertIs(mathparse.parse("-2 == -2"), True)
57
+
58
+ def test_lower_precedence_than_arithmetic(self):
59
+ # (1 + 2) <= 4, not 1 + (2 <= 4)
60
+ self.assertIs(mathparse.parse("1 + 2 <= 4"), True)
61
+ self.assertIs(mathparse.parse("2 * 3 > 5"), True)
62
+ self.assertIs(mathparse.parse("2 ^ 3 == 8"), True)
63
+ self.assertIs(mathparse.parse("10 % 4 != 2"), False)
64
+
65
+ def test_both_sides_are_evaluated(self):
66
+ self.assertIs(mathparse.parse("1 + 2 < 2 * 2"), True)
67
+ self.assertIs(mathparse.parse("10 / 2 >= 3 + 2"), True)
68
+
69
+ def test_parentheses(self):
70
+ self.assertIs(mathparse.parse("(3 < 5)"), True)
71
+ self.assertIs(mathparse.parse("(1 + 2) * 2 == 6"), True)
72
+
73
+ def test_unary_functions(self):
74
+ self.assertIs(mathparse.parse("sqrt 16 == 4"), True)
75
+ self.assertIs(mathparse.parse("sqrt 16 < 3"), False)
76
+
77
+ def test_constants(self):
78
+ self.assertIs(mathparse.parse("pi > 3"), True)
79
+ self.assertIs(mathparse.parse("e >= 3"), False)
80
+
81
+ def test_function_arguments(self):
82
+ self.assertIs(mathparse.parse("max(3, 7) == 7"), True)
83
+ self.assertIs(mathparse.parse("min(3, 7) > 3"), False)
84
+
85
+ def test_division_result(self):
86
+ self.assertIs(mathparse.parse("1 / 3 < 0.5"), True)
87
+
88
+ def test_result_can_be_used_in_arithmetic(self):
89
+ # True is 1 and False is 0
90
+ self.assertEqual(mathparse.parse("(3 < 5) + 1"), 2)
91
+ self.assertEqual(mathparse.parse("(3 > 5) + 1"), 1)
92
+
93
+ def test_chained_comparisons_are_left_associative(self):
94
+ # (1 < 2) < 3 is True < 3 is True
95
+ self.assertIs(mathparse.parse("1 < 2 < 3"), True)
96
+ # (3 < 2) == 0 is False == 0 is True
97
+ self.assertIs(mathparse.parse("3 < 2 == 0"), True)
98
+
99
+ def test_missing_operand(self):
100
+ with self.assertRaises(mathparse.PostfixTokenEvaluationException):
101
+ mathparse.parse("3 <=")
102
+
103
+ def test_is_symbol(self):
104
+ for operator in ["<", ">", "<=", ">=", "==", "!="]:
105
+ self.assertTrue(mathparse.is_symbol(operator))
106
+ self.assertTrue(mathparse.is_binary(operator))
107
+
108
+
109
+ class ComparisonWordsTestCase(TestCase):
110
+
111
+ def test_greater_than_words(self):
112
+ self.assertIs(mathparse.parse("five greater than three", language="ENG"), True)
113
+
114
+ def test_less_than_words(self):
115
+ self.assertIs(mathparse.parse("five less than three", language="ENG"), False)
116
+
117
+ def test_greater_than_or_equal_to_words(self):
118
+ result = mathparse.parse("five greater than or equal to five", language="ENG")
119
+ self.assertIs(result, True)
120
+
121
+ def test_less_than_or_equal_to_words(self):
122
+ result = mathparse.parse("six less than or equal to five", language="ENG")
123
+ self.assertIs(result, False)
124
+
125
+ def test_equals_words(self):
126
+ self.assertIs(mathparse.parse("two plus two equals four", language="ENG"), True)
127
+ self.assertIs(mathparse.parse("two plus two equal to five", language="ENG"), False)
128
+
129
+ def test_not_equal_to_words(self):
130
+ result = mathparse.parse("two plus two not equal to five", language="ENG")
131
+ self.assertIs(result, True)
132
+
133
+ def test_words_mixed_with_symbols(self):
134
+ self.assertIs(mathparse.parse("ten minus three >= 7", language="ENG"), True)
135
+
136
+ def test_extract_expression(self):
137
+ result = mathparse.extract_expression("Is it true that 3 + 4 >= 7?", language="ENG")
138
+ self.assertEqual(result, "3 + 4 >= 7")
@@ -0,0 +1,94 @@
1
+ from unittest import TestCase
2
+ from mathparse import mathparse
3
+
4
+
5
+ class HexNumberTestCase(TestCase):
6
+
7
+ def test_single_hex_number(self):
8
+ self.assertEqual(mathparse.parse("0x44"), 68)
9
+ self.assertEqual(mathparse.parse("0x0"), 0)
10
+ self.assertEqual(mathparse.parse("0xff"), 255)
11
+
12
+ def test_uppercase(self):
13
+ self.assertEqual(mathparse.parse("0XFF"), 255)
14
+ self.assertEqual(mathparse.parse("0xAbCd"), 43981)
15
+
16
+ def test_addition(self):
17
+ self.assertEqual(mathparse.parse("0x44 + 0x40"), 132)
18
+
19
+ def test_multiplication(self):
20
+ self.assertEqual(mathparse.parse("0x7*8"), 56)
21
+
22
+ def test_mixed_with_decimal(self):
23
+ self.assertEqual(mathparse.parse("0x10 + 1"), 17)
24
+ self.assertEqual(mathparse.parse("100 - 0x1"), 99)
25
+
26
+ def test_negative_hex(self):
27
+ self.assertEqual(mathparse.parse("-0x10"), -16)
28
+ self.assertEqual(mathparse.parse("0x10 - -0x10"), 32)
29
+
30
+ def test_bitwise_shift(self):
31
+ self.assertEqual(mathparse.parse("0x1 << 4"), 16)
32
+ self.assertEqual(mathparse.parse("0xff >> 4"), 15)
33
+
34
+ def test_comparison(self):
35
+ self.assertIs(mathparse.parse("0x10 == 16"), True)
36
+ self.assertIs(mathparse.parse("0x10 < 0xf"), False)
37
+
38
+ def test_parentheses(self):
39
+ self.assertEqual(mathparse.parse("(0x2 + 0x3) * 0x4"), 20)
40
+
41
+ def test_hex_looking_like_scientific_notation(self):
42
+ # "1e3" inside a hex literal is hex digits, not exponent notation
43
+ self.assertEqual(mathparse.parse("0x1e3"), 483)
44
+
45
+ def test_tokenize_converts_in_place(self):
46
+ self.assertEqual(mathparse.tokenize("0x44 + 0x40"), ["68", "+", "64"])
47
+ self.assertEqual(mathparse.tokenize("0x7*8"), ["7", "*", "8"])
48
+
49
+ def test_not_part_of_larger_word(self):
50
+ # "10x44" is not a hex literal and must not be rewritten
51
+ self.assertNotIn("68", mathparse.tokenize("10x44"))
52
+
53
+ def test_extract_expression(self):
54
+ self.assertEqual(
55
+ mathparse.extract_expression("what is 0x44 + 0x40 please", "ENG"),
56
+ "68 + 64",
57
+ )
58
+
59
+ def test_language_words_with_hex(self):
60
+ self.assertEqual(mathparse.parse("0x10 plus two", "ENG"), 18)
61
+
62
+
63
+ class HexFunctionTestCase(TestCase):
64
+
65
+ def test_hex_function(self):
66
+ self.assertEqual(mathparse.parse("hex(371200)"), "0x5aa00")
67
+ self.assertEqual(mathparse.parse("hex(0)"), "0x0")
68
+ self.assertEqual(mathparse.parse("hex(255)"), "0xff")
69
+
70
+ def test_hex_function_without_parentheses(self):
71
+ self.assertEqual(mathparse.parse("hex 16"), "0x10")
72
+
73
+ def test_hex_of_expression(self):
74
+ self.assertEqual(mathparse.parse("hex(200 + 55)"), "0xff")
75
+ self.assertEqual(mathparse.parse("hex(0x10 * 2)"), "0x20")
76
+
77
+ def test_hex_of_negative(self):
78
+ self.assertEqual(mathparse.parse("hex(-16)"), "-0x10")
79
+
80
+ def test_hex_of_integral_float(self):
81
+ self.assertEqual(mathparse.parse("hex(4.0)"), "0x4")
82
+ self.assertEqual(mathparse.parse("hex(sqrt(16))"), "0x4")
83
+
84
+ def test_hex_of_fraction_raises(self):
85
+ with self.assertRaises(ValueError):
86
+ mathparse.parse("hex(2.5)")
87
+
88
+ def test_hex_result_in_arithmetic(self):
89
+ self.assertEqual(mathparse.parse("hex(4) + 1"), 5)
90
+ self.assertEqual(mathparse.parse("hex(hex(255))"), "0xff")
91
+
92
+ def test_hex_english(self):
93
+ self.assertEqual(mathparse.parse("hex(twenty)", "ENG"), "0x14")
94
+ self.assertEqual(mathparse.parse("hex thirty two", "ENG"), "0x20")
@@ -3,7 +3,6 @@ from mathparse import mathparse
3
3
 
4
4
 
5
5
  class ExpressionLimitTestCase(TestCase):
6
-
7
6
  def setUp(self):
8
7
  self.max_expression_length = mathparse.MAX_EXPRESSION_LENGTH
9
8
  self.max_integer_digits = mathparse.MAX_INTEGER_DIGITS
@@ -14,57 +13,53 @@ class ExpressionLimitTestCase(TestCase):
14
13
 
15
14
  def test_huge_power(self):
16
15
  with self.assertRaises(mathparse.ExpressionTooLargeException):
17
- mathparse.parse('999999**999999999')
16
+ mathparse.parse("999999**999999999")
18
17
 
19
18
  def test_huge_power_tower(self):
20
19
  with self.assertRaises(mathparse.ExpressionTooLargeException):
21
- mathparse.parse('9 ^ 9 ^ 9')
22
-
23
- def test_power_at_limit(self):
24
- # 10 ^ 999 has exactly 1000 digits
25
- self.assertEqual(mathparse.parse('10 ^ 999'), 10 ** 999)
20
+ mathparse.parse("9 ^ 9 ^ 9")
26
21
 
27
22
  def test_power_over_limit(self):
28
23
  with self.assertRaises(mathparse.ExpressionTooLargeException):
29
- mathparse.parse('10 ^ 1000')
24
+ mathparse.parse("10 ^ 1000")
30
25
 
31
26
  def test_power_of_one_is_not_limited(self):
32
- self.assertEqual(mathparse.parse('1 ^ 999999999'), 1)
27
+ self.assertEqual(mathparse.parse("1 ^ 999999999"), 1)
33
28
 
34
29
  def test_huge_factorial(self):
35
30
  with self.assertRaises(mathparse.ExpressionTooLargeException):
36
- mathparse.parse('factorial 10000000')
31
+ mathparse.parse("factorial 10000000")
37
32
 
38
33
  def test_repeated_multiplication(self):
39
34
  with self.assertRaises(mathparse.ExpressionTooLargeException):
40
- mathparse.parse('(2 ^ 3000) * (2 ^ 3000)')
35
+ mathparse.parse("(2 ^ 3000) * (2 ^ 3000)")
41
36
 
42
37
  def test_float_overflow(self):
43
38
  with self.assertRaises(mathparse.ExpressionTooLargeException):
44
- mathparse.parse('1.5 ** 999999999')
39
+ mathparse.parse("1.5 ** 999999999")
45
40
 
46
41
  def test_function_overflow(self):
47
42
  with self.assertRaises(mathparse.ExpressionTooLargeException):
48
- mathparse.parse('exp(1000)')
43
+ mathparse.parse("exp(1000)")
49
44
 
50
45
  def test_long_expression(self):
51
46
  with self.assertRaises(mathparse.ExpressionTooLargeException):
52
- mathparse.parse('1' + ' + 1' * 500)
47
+ mathparse.parse("1" + " + 1" * 500)
53
48
 
54
49
  def test_is_postfix_evaluation_exception(self):
55
50
  # Existing handlers for evaluation errors also catch size errors
56
51
  with self.assertRaises(mathparse.PostfixTokenEvaluationException):
57
- mathparse.parse('999999 ^ 999999999')
52
+ mathparse.parse("999999 ^ 999999999")
58
53
 
59
54
  def test_custom_integer_digit_limit(self):
60
55
  mathparse.MAX_INTEGER_DIGITS = 10
61
56
  with self.assertRaises(mathparse.ExpressionTooLargeException):
62
- mathparse.parse('10 ^ 10')
57
+ mathparse.parse("10 ^ 10")
63
58
 
64
59
  def test_disabled_integer_digit_limit(self):
65
60
  mathparse.MAX_INTEGER_DIGITS = None
66
- self.assertEqual(mathparse.parse('2 ^ 5000'), 2 ** 5000)
61
+ self.assertEqual(mathparse.parse("2 ^ 5000"), 2**5000)
67
62
 
68
63
  def test_disabled_expression_length_limit(self):
69
64
  mathparse.MAX_EXPRESSION_LENGTH = None
70
- self.assertEqual(mathparse.parse('1' + ' + 1' * 500), 501)
65
+ self.assertEqual(mathparse.parse("1" + " + 1" * 500), 501)