azrideus-mathparse 0.2.15__tar.gz → 0.2.17__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 (35) hide show
  1. {azrideus_mathparse-0.2.15 → azrideus_mathparse-0.2.17}/PKG-INFO +1 -1
  2. {azrideus_mathparse-0.2.15 → azrideus_mathparse-0.2.17}/azrideus_mathparse.egg-info/PKG-INFO +1 -1
  3. {azrideus_mathparse-0.2.15 → azrideus_mathparse-0.2.17}/mathparse/__init__.py +1 -1
  4. {azrideus_mathparse-0.2.15 → azrideus_mathparse-0.2.17}/mathparse/evaluator.py +239 -220
  5. {azrideus_mathparse-0.2.15 → azrideus_mathparse-0.2.17}/tests/test_binary_operations.py +345 -298
  6. {azrideus_mathparse-0.2.15 → azrideus_mathparse-0.2.17}/LICENSE +0 -0
  7. {azrideus_mathparse-0.2.15 → azrideus_mathparse-0.2.17}/README.md +0 -0
  8. {azrideus_mathparse-0.2.15 → azrideus_mathparse-0.2.17}/azrideus_mathparse.egg-info/SOURCES.txt +0 -0
  9. {azrideus_mathparse-0.2.15 → azrideus_mathparse-0.2.17}/azrideus_mathparse.egg-info/dependency_links.txt +0 -0
  10. {azrideus_mathparse-0.2.15 → azrideus_mathparse-0.2.17}/azrideus_mathparse.egg-info/requires.txt +0 -0
  11. {azrideus_mathparse-0.2.15 → azrideus_mathparse-0.2.17}/azrideus_mathparse.egg-info/top_level.txt +0 -0
  12. {azrideus_mathparse-0.2.15 → azrideus_mathparse-0.2.17}/mathparse/exceptions.py +0 -0
  13. {azrideus_mathparse-0.2.15 → azrideus_mathparse-0.2.17}/mathparse/extraction.py +0 -0
  14. {azrideus_mathparse-0.2.15 → azrideus_mathparse-0.2.17}/mathparse/limits.py +0 -0
  15. {azrideus_mathparse-0.2.15 → azrideus_mathparse-0.2.17}/mathparse/mathparse.py +0 -0
  16. {azrideus_mathparse-0.2.15 → azrideus_mathparse-0.2.17}/mathparse/mathwords.py +0 -0
  17. {azrideus_mathparse-0.2.15 → azrideus_mathparse-0.2.17}/mathparse/patterns.py +0 -0
  18. {azrideus_mathparse-0.2.15 → azrideus_mathparse-0.2.17}/mathparse/postfix.py +0 -0
  19. {azrideus_mathparse-0.2.15 → azrideus_mathparse-0.2.17}/mathparse/tokenizer.py +0 -0
  20. {azrideus_mathparse-0.2.15 → azrideus_mathparse-0.2.17}/mathparse/tokens.py +0 -0
  21. {azrideus_mathparse-0.2.15 → azrideus_mathparse-0.2.17}/mathparse/word_tokens.py +0 -0
  22. {azrideus_mathparse-0.2.15 → azrideus_mathparse-0.2.17}/pyproject.toml +0 -0
  23. {azrideus_mathparse-0.2.15 → azrideus_mathparse-0.2.17}/setup.cfg +0 -0
  24. {azrideus_mathparse-0.2.15 → azrideus_mathparse-0.2.17}/tests/test_bitshift_operations.py +0 -0
  25. {azrideus_mathparse-0.2.15 → azrideus_mathparse-0.2.17}/tests/test_bitwise_operations.py +0 -0
  26. {azrideus_mathparse-0.2.15 → azrideus_mathparse-0.2.17}/tests/test_comparison_operations.py +0 -0
  27. {azrideus_mathparse-0.2.15 → azrideus_mathparse-0.2.17}/tests/test_complex_statements.py +0 -0
  28. {azrideus_mathparse-0.2.15 → azrideus_mathparse-0.2.17}/tests/test_hex_numbers.py +0 -0
  29. {azrideus_mathparse-0.2.15 → azrideus_mathparse-0.2.17}/tests/test_language_support.py +0 -0
  30. {azrideus_mathparse-0.2.15 → azrideus_mathparse-0.2.17}/tests/test_limits.py +0 -0
  31. {azrideus_mathparse-0.2.15 → azrideus_mathparse-0.2.17}/tests/test_prefix_unary_operations.py +0 -0
  32. {azrideus_mathparse-0.2.15 → azrideus_mathparse-0.2.17}/tests/test_replace_word_tokens.py +0 -0
  33. {azrideus_mathparse-0.2.15 → azrideus_mathparse-0.2.17}/tests/test_simplified_chinese.py +0 -0
  34. {azrideus_mathparse-0.2.15 → azrideus_mathparse-0.2.17}/tests/test_unary_operations.py +0 -0
  35. {azrideus_mathparse-0.2.15 → azrideus_mathparse-0.2.17}/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.15
3
+ Version: 0.2.17
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.15
3
+ Version: 0.2.17
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.15"
5
+ __version__ = "0.2.17"
@@ -1,220 +1,239 @@
1
- """
2
- Evaluation of expressions in postfix (reverse Polish) notation.
3
- """
4
-
5
- from decimal import Decimal
6
- from typing import Union
7
- from . import mathwords
8
- from .exceptions import PostfixTokenEvaluationException
9
- from .limits import check_integer_digits
10
- from .tokens import is_constant, is_float, is_hex, is_int, is_unary, to_number
11
- import math
12
-
13
-
14
- COMPARISON_FUNCTIONS = {
15
- "<": lambda a, b: a < b,
16
- ">": lambda a, b: a > b,
17
- "<=": lambda a, b: a <= b,
18
- ">=": lambda a, b: a >= b,
19
- "==": lambda a, b: a == b,
20
- "!=": lambda a, b: a != b,
21
- }
22
-
23
-
24
- def evaluate_postfix(tokens: list) -> Union[int, float, str, Decimal]:
25
- """
26
- Given a list of evaluatable tokens in postfix format,
27
- calculate a solution.
28
- """
29
- stack = []
30
-
31
- for token in tokens:
32
- total = None
33
-
34
- if is_int(token) or is_float(token) or is_constant(token):
35
- stack.append(token)
36
- elif is_unary(token):
37
- a = stack.pop()
38
- # Convert token (string) to number for unary function evaluation
39
- a = to_number(a)
40
- function = mathwords.UNARY_FUNCTIONS[token]
41
- # Check the size of n! (using log(n!) = lgamma(n + 1)) before
42
- # computing it, since a large factorial is slow to calculate
43
- if function is math.factorial and isinstance(a, int) and a > 1:
44
- check_integer_digits(math.lgamma(a + 1) / math.log(10), token)
45
- if isinstance(a, mathwords.ArgumentList) and not getattr(
46
- function, "variadic", False
47
- ):
48
- raise PostfixTokenEvaluationException(
49
- 'Function "{}" takes a single argument'.format(token)
50
- )
51
- total = function(a)
52
- elif len(stack) == 1:
53
- raise PostfixTokenEvaluationException(
54
- 'Insufficient values in expression for operator "{}"'.format(token)
55
- )
56
- elif len(stack) > 1:
57
- b = stack.pop()
58
- a = stack.pop()
59
-
60
- if token != "," and (
61
- isinstance(a, mathwords.ArgumentList)
62
- or isinstance(b, mathwords.ArgumentList)
63
- ):
64
- raise PostfixTokenEvaluationException(
65
- "Comma separated values can only be used as function "
66
- "arguments, such as max(3, 7)"
67
- )
68
-
69
- if token == ",":
70
- # Collect comma separated function arguments into a list
71
- # Example: 3 , 7 , 5 = [3, 7, 5]
72
- if isinstance(a, mathwords.ArgumentList):
73
- total = a
74
- else:
75
- total = mathwords.ArgumentList([to_number(a)])
76
- total.append(to_number(b))
77
- elif token == "+":
78
- total = to_number(a) + to_number(b)
79
- elif token == "-":
80
- total = to_number(a) - to_number(b)
81
- elif token == "*":
82
- total = to_number(a) * to_number(b)
83
- elif token == "^":
84
- base = to_number(a)
85
- exponent = to_number(b)
86
- # Check the size of an integer power before computing it,
87
- # since a huge power (e.g. 999999 ^ 999999999) would use all
88
- # available memory. Float and Decimal powers instead raise an
89
- # overflow error quickly.
90
- if (
91
- isinstance(base, int)
92
- and isinstance(exponent, int)
93
- and exponent > 0
94
- and abs(base) > 1
95
- ):
96
- check_integer_digits(exponent * math.log10(abs(base)), token)
97
- total = base**exponent
98
- elif token == "/":
99
- # Convert tokens such as constants (e.g. "pi") to numbers
100
- # before passing them to Decimal
101
- if to_number(b) == 0:
102
- total = "undefined"
103
- else:
104
- total = Decimal(str(to_number(a))) / Decimal(str(to_number(b)))
105
- elif token == "%":
106
- if to_number(b) == 0:
107
- total = "undefined"
108
- else:
109
- total = to_number(a) % to_number(b)
110
- elif token in mathwords.COMPARISON_OPERATORS:
111
- total = COMPARISON_FUNCTIONS[token](to_number(a), to_number(b))
112
- elif token in mathwords.SHIFT_OPERATORS:
113
- value = to_number(a)
114
- count = to_number(b)
115
- # Bit shifts are only defined for integers (True and False
116
- # count as 1 and 0)
117
- if not isinstance(value, int) or not isinstance(count, int):
118
- raise PostfixTokenEvaluationException(
119
- 'Bit shift operator "{}" requires integer operands'.format(
120
- token
121
- )
122
- )
123
- if count < 0:
124
- raise PostfixTokenEvaluationException(
125
- 'Bit shift operator "{}" requires a non-negative shift '
126
- "count".format(token)
127
- )
128
- if token == "<<":
129
- # Check the size of the result before computing it, since
130
- # a huge shift (e.g. 1 << 999999999) would use all
131
- # available memory. Each shift multiplies the value by 2.
132
- if value != 0:
133
- check_integer_digits(
134
- math.log10(abs(value)) + count * math.log10(2), token
135
- )
136
- total = value << count
137
- else:
138
- total = value >> count
139
- elif token in mathwords.BITWISE_OPERATORS:
140
- left = to_number(a)
141
- right = to_number(b)
142
- # Bitwise operators are only defined for integers (True and
143
- # False count as 1 and 0). The result is never larger than
144
- # the larger operand, so no size check is needed.
145
- if not isinstance(left, int) or not isinstance(right, int):
146
- raise PostfixTokenEvaluationException(
147
- 'Bitwise operator "{}" requires integer operands'.format(
148
- token
149
- )
150
- )
151
- if token == "&":
152
- total = int(left) & int(right)
153
- else:
154
- total = int(left) | int(right)
155
- elif token == ".":
156
- # Treat decimal points as a binary operator that combines the
157
- # integer and fractional part of two numbers
158
- # Example: 53 . 25 = 53.25, -3 . 5 = -3.5
159
-
160
- # Convert b to number
161
- numeric_b = to_number(b)
162
-
163
- if numeric_b == 0:
164
- # Convert a to number
165
- numeric_a = to_number(a)
166
- total = Decimal(numeric_a)
167
- else:
168
- # Check if 'a' has a negative sign (handles -0 case)
169
- is_negative = str(a).startswith("-")
170
-
171
- # Convert a to number for calculation
172
- numeric_a = to_number(a)
173
-
174
- # Count the digits in the original string b to preserve
175
- # leading zeros (e.g., "01" has 2 digits, not 1)
176
- digits = len(str(b))
177
- divisor = 10**digits
178
- fractional_part = numeric_b / divisor
179
-
180
- # Handle negatives: -3 . 5 = -3.5, not -2.5
181
- # Also -0 . 5 = -0.5 (check string since -0 == 0)
182
- if is_negative:
183
- total = numeric_a - fractional_part
184
- else:
185
- total = numeric_a + fractional_part
186
- else:
187
- raise PostfixTokenEvaluationException(
188
- 'Unknown token "{}"'.format(token)
189
- )
190
-
191
- # Limit the size of every computed integer, which also prevents
192
- # repeated operations such as multiplication from growing a number
193
- # without bound
194
- if isinstance(total, int) and total:
195
- check_integer_digits((total.bit_length() - 1) * math.log10(2), token)
196
-
197
- if total is not None:
198
- stack.append(total)
199
-
200
- # If the stack is empty the tokens could not be evaluated
201
- if not stack:
202
- raise PostfixTokenEvaluationException(
203
- "The postfix expression resulted in an empty stack"
204
- )
205
-
206
- result = stack.pop()
207
-
208
- if isinstance(result, mathwords.ArgumentList):
209
- raise PostfixTokenEvaluationException(
210
- "Comma separated values can only be used as function arguments, "
211
- "such as max(3, 7)"
212
- )
213
-
214
- # Convert final result from string (such as "4" or a constant like "pi")
215
- # to a number if needed. A hexadecimal string produced by hex() is kept
216
- # as-is, since that is the requested output format.
217
- if isinstance(result, str) and not is_hex(result):
218
- result = to_number(result)
219
-
220
- return result
1
+ """
2
+ Evaluation of expressions in postfix (reverse Polish) notation.
3
+ """
4
+
5
+ from decimal import Decimal
6
+ from typing import Union
7
+ from . import mathwords
8
+ from .exceptions import PostfixTokenEvaluationException
9
+ from .limits import check_integer_digits
10
+ from .tokens import is_constant, is_float, is_hex, is_int, is_unary, to_number
11
+ import math
12
+
13
+
14
+ COMPARISON_FUNCTIONS = {
15
+ "<": lambda a, b: a < b,
16
+ ">": lambda a, b: a > b,
17
+ "<=": lambda a, b: a <= b,
18
+ ">=": lambda a, b: a >= b,
19
+ "==": lambda a, b: a == b,
20
+ "!=": lambda a, b: a != b,
21
+ }
22
+
23
+
24
+ def to_numbers(a, b) -> tuple:
25
+ """
26
+ Convert two operands to numbers that can be used together.
27
+ Division returns a Decimal, which Python can not combine with a float,
28
+ so a float is converted to a Decimal when the other operand is one.
29
+ Example: (10 / 4) - 1.5 = Decimal('2.5') - Decimal('1.5')
30
+ """
31
+ a = to_number(a)
32
+ b = to_number(b)
33
+ if isinstance(a, Decimal) and isinstance(b, float):
34
+ b = Decimal(str(b))
35
+ elif isinstance(b, Decimal) and isinstance(a, float):
36
+ a = Decimal(str(a))
37
+ return a, b
38
+
39
+
40
+ def evaluate_postfix(tokens: list) -> Union[int, float, str, Decimal]:
41
+ """
42
+ Given a list of evaluatable tokens in postfix format,
43
+ calculate a solution.
44
+ """
45
+ stack = []
46
+
47
+ for token in tokens:
48
+ total = None
49
+
50
+ if is_int(token) or is_float(token) or is_constant(token):
51
+ stack.append(token)
52
+ elif is_unary(token):
53
+ a = stack.pop()
54
+ # Convert token (string) to number for unary function evaluation
55
+ a = to_number(a)
56
+ function = mathwords.UNARY_FUNCTIONS[token]
57
+ # Check the size of n! (using log(n!) = lgamma(n + 1)) before
58
+ # computing it, since a large factorial is slow to calculate
59
+ if function is math.factorial and isinstance(a, int) and a > 1:
60
+ check_integer_digits(math.lgamma(a + 1) / math.log(10), token)
61
+ if isinstance(a, mathwords.ArgumentList) and not getattr(
62
+ function, "variadic", False
63
+ ):
64
+ raise PostfixTokenEvaluationException(
65
+ 'Function "{}" takes a single argument'.format(token)
66
+ )
67
+ total = function(a)
68
+ elif len(stack) == 1:
69
+ raise PostfixTokenEvaluationException(
70
+ 'Insufficient values in expression for operator "{}"'.format(token)
71
+ )
72
+ elif len(stack) > 1:
73
+ b = stack.pop()
74
+ a = stack.pop()
75
+
76
+ if token != "," and (
77
+ isinstance(a, mathwords.ArgumentList)
78
+ or isinstance(b, mathwords.ArgumentList)
79
+ ):
80
+ raise PostfixTokenEvaluationException(
81
+ "Comma separated values can only be used as function "
82
+ "arguments, such as max(3, 7)"
83
+ )
84
+
85
+ if token == ",":
86
+ # Collect comma separated function arguments into a list
87
+ # Example: 3 , 7 , 5 = [3, 7, 5]
88
+ if isinstance(a, mathwords.ArgumentList):
89
+ total = a
90
+ else:
91
+ total = mathwords.ArgumentList([to_number(a)])
92
+ total.append(to_number(b))
93
+ elif token == "+":
94
+ x, y = to_numbers(a, b)
95
+ total = x + y
96
+ elif token == "-":
97
+ x, y = to_numbers(a, b)
98
+ total = x - y
99
+ elif token == "*":
100
+ x, y = to_numbers(a, b)
101
+ total = x * y
102
+ elif token == "^":
103
+ base, exponent = to_numbers(a, b)
104
+ # Check the size of an integer power before computing it,
105
+ # since a huge power (e.g. 999999 ^ 999999999) would use all
106
+ # available memory. Float and Decimal powers instead raise an
107
+ # overflow error quickly.
108
+ if (
109
+ isinstance(base, int)
110
+ and isinstance(exponent, int)
111
+ and exponent > 0
112
+ and abs(base) > 1
113
+ ):
114
+ check_integer_digits(exponent * math.log10(abs(base)), token)
115
+ total = base**exponent
116
+ elif token == "/":
117
+ # Convert tokens such as constants (e.g. "pi") to numbers
118
+ # before passing them to Decimal
119
+ if to_number(b) == 0:
120
+ total = "undefined"
121
+ else:
122
+ total = Decimal(str(to_number(a))) / Decimal(str(to_number(b)))
123
+ elif token == "%":
124
+ if to_number(b) == 0:
125
+ total = "undefined"
126
+ else:
127
+ x, y = to_numbers(a, b)
128
+ total = x % y
129
+ elif token in mathwords.COMPARISON_OPERATORS:
130
+ total = COMPARISON_FUNCTIONS[token](*to_numbers(a, b))
131
+ elif token in mathwords.SHIFT_OPERATORS:
132
+ value = to_number(a)
133
+ count = to_number(b)
134
+ # Bit shifts are only defined for integers (True and False
135
+ # count as 1 and 0)
136
+ if not isinstance(value, int) or not isinstance(count, int):
137
+ raise PostfixTokenEvaluationException(
138
+ 'Bit shift operator "{}" requires integer operands'.format(
139
+ token
140
+ )
141
+ )
142
+ if count < 0:
143
+ raise PostfixTokenEvaluationException(
144
+ 'Bit shift operator "{}" requires a non-negative shift '
145
+ "count".format(token)
146
+ )
147
+ if token == "<<":
148
+ # Check the size of the result before computing it, since
149
+ # a huge shift (e.g. 1 << 999999999) would use all
150
+ # available memory. Each shift multiplies the value by 2.
151
+ if value != 0:
152
+ check_integer_digits(
153
+ math.log10(abs(value)) + count * math.log10(2), token
154
+ )
155
+ total = value << count
156
+ else:
157
+ total = value >> count
158
+ elif token in mathwords.BITWISE_OPERATORS:
159
+ left = to_number(a)
160
+ right = to_number(b)
161
+ # Bitwise operators are only defined for integers (True and
162
+ # False count as 1 and 0). The result is never larger than
163
+ # the larger operand, so no size check is needed.
164
+ if not isinstance(left, int) or not isinstance(right, int):
165
+ raise PostfixTokenEvaluationException(
166
+ 'Bitwise operator "{}" requires integer operands'.format(
167
+ token
168
+ )
169
+ )
170
+ if token == "&":
171
+ total = int(left) & int(right)
172
+ else:
173
+ total = int(left) | int(right)
174
+ elif token == ".":
175
+ # Treat decimal points as a binary operator that combines the
176
+ # integer and fractional part of two numbers
177
+ # Example: 53 . 25 = 53.25, -3 . 5 = -3.5
178
+
179
+ # Convert b to number
180
+ numeric_b = to_number(b)
181
+
182
+ if numeric_b == 0:
183
+ # Convert a to number
184
+ numeric_a = to_number(a)
185
+ total = Decimal(numeric_a)
186
+ else:
187
+ # Check if 'a' has a negative sign (handles -0 case)
188
+ is_negative = str(a).startswith("-")
189
+
190
+ # Convert a to number for calculation
191
+ numeric_a = to_number(a)
192
+
193
+ # Count the digits in the original string b to preserve
194
+ # leading zeros (e.g., "01" has 2 digits, not 1)
195
+ digits = len(str(b))
196
+ divisor = 10**digits
197
+ fractional_part = numeric_b / divisor
198
+
199
+ # Handle negatives: -3 . 5 = -3.5, not -2.5
200
+ # Also -0 . 5 = -0.5 (check string since -0 == 0)
201
+ if is_negative:
202
+ total = numeric_a - fractional_part
203
+ else:
204
+ total = numeric_a + fractional_part
205
+ else:
206
+ raise PostfixTokenEvaluationException(
207
+ 'Unknown token "{}"'.format(token)
208
+ )
209
+
210
+ # Limit the size of every computed integer, which also prevents
211
+ # repeated operations such as multiplication from growing a number
212
+ # without bound
213
+ if isinstance(total, int) and total:
214
+ check_integer_digits((total.bit_length() - 1) * math.log10(2), token)
215
+
216
+ if total is not None:
217
+ stack.append(total)
218
+
219
+ # If the stack is empty the tokens could not be evaluated
220
+ if not stack:
221
+ raise PostfixTokenEvaluationException(
222
+ "The postfix expression resulted in an empty stack"
223
+ )
224
+
225
+ result = stack.pop()
226
+
227
+ if isinstance(result, mathwords.ArgumentList):
228
+ raise PostfixTokenEvaluationException(
229
+ "Comma separated values can only be used as function arguments, "
230
+ "such as max(3, 7)"
231
+ )
232
+
233
+ # Convert final result from string (such as "4" or a constant like "pi")
234
+ # to a number if needed. A hexadecimal string produced by hex() is kept
235
+ # as-is, since that is the requested output format.
236
+ if isinstance(result, str) and not is_hex(result):
237
+ result = to_number(result)
238
+
239
+ return result
@@ -1,298 +1,345 @@
1
- from unittest import TestCase
2
- from mathparse import mathparse, mathwords
3
-
4
-
5
- class PositiveIntegerTestCase(TestCase):
6
- def test_addition(self):
7
- result = mathparse.parse("4 + 4")
8
-
9
- self.assertEqual(result, 8)
10
-
11
- def test_addition_words(self):
12
- result = mathparse.parse("four plus four", language="ENG")
13
-
14
- self.assertEqual(result, 8)
15
-
16
- def test_addition_words_large(self):
17
- result = mathparse.parse(
18
- "four thousand two hundred one plus five hundred", language="ENG"
19
- )
20
-
21
- self.assertEqual(result, 4701)
22
-
23
- def test_subtraction(self):
24
- result = mathparse.parse("30 - 20")
25
-
26
- self.assertEqual(result, 10)
27
-
28
- def test_subtraction_words(self):
29
- result = mathparse.parse("thirty minus twenty", language="ENG")
30
-
31
- self.assertEqual(result, 10)
32
-
33
- def test_multiplication(self):
34
- result = mathparse.parse("9 * 9")
35
-
36
- self.assertEqual(result, 81)
37
-
38
- def test_multiplication_words(self):
39
- result = mathparse.parse("nine times nine", language="ENG")
40
-
41
- self.assertEqual(result, 81)
42
-
43
- def test_division(self):
44
- result = mathparse.parse("15 / 5")
45
-
46
- self.assertEqual(result, 3)
47
-
48
- def test_division_words(self):
49
- result = mathparse.parse("fifteen divided by five", language="ENG")
50
-
51
- self.assertEqual(result, 3)
52
-
53
- def test_double_digit_multiplier_for_scale_addition(self):
54
- result = mathparse.parse("fifty thousand plus one", language="ENG")
55
-
56
- self.assertEqual(result, 50001)
57
-
58
- def test_division_by_zero(self):
59
- result = mathparse.parse("42 / 0", language="ENG")
60
-
61
- self.assertEqual(result, "undefined")
62
-
63
- def test_division_by_zero_words(self):
64
- result = mathparse.parse("six divided by zero", language="ENG")
65
-
66
- self.assertEqual(result, "undefined")
67
-
68
- def test_division_words_large(self):
69
- result = mathparse.parse(
70
- "one thousand two hundred four divided by one hundred", language="ENG"
71
- )
72
-
73
- self.assertEqual(str(result), "12.04")
74
-
75
- def test_operation_precedence(self):
76
- result = mathparse.parse("2 + 3 * (4 - 2) ^ 2 / 2")
77
-
78
- self.assertEqual(result, 8)
79
-
80
- def test_tokens_with_extra_spaces(self):
81
- result = mathparse.parse(" 2 + 3 * ( 4 - 2 ) ^ 2 / 2 ")
82
-
83
- self.assertEqual(result, 8)
84
-
85
- def test_tokens_with_no_spaces(self):
86
- result = mathparse.parse("2+3*(4-2)^2/2")
87
-
88
- self.assertEqual(result, 8)
89
-
90
-
91
- class PositiveFloatTestCase(TestCase):
92
- def test_addition(self):
93
- result = mathparse.parse("0.6 + 0.5")
94
-
95
- self.assertEqual(result, 1.1)
96
-
97
- def test_subtraction(self):
98
- result = mathparse.parse("30.1 - 29.1")
99
-
100
- self.assertEqual(result, 1)
101
-
102
- def test_multiplication(self):
103
- result = mathparse.parse("0.9 * 0.9")
104
-
105
- self.assertEqual(result, 0.81)
106
-
107
- def test_division(self):
108
- result = mathparse.parse("0.6 / 0.2")
109
-
110
- self.assertEqual(result, 3)
111
-
112
-
113
- class WordOperatorTestCase(TestCase):
114
- def test_power_of(self):
115
- result = mathparse.parse("2 to the power of 3", language="ENG")
116
-
117
- self.assertEqual(result, 8)
118
-
119
-
120
- class WordBasedDecimalTestCase(TestCase):
121
- """
122
- Test cases for word-based decimal numbers.
123
- For example: "fifty three point four" should be treated as 53.4
124
- """
125
-
126
- def test_word_decimal_with_multiplication(self):
127
- """
128
- Test: "Fifty three point four times seven" should equal 53.4 * 7
129
- """
130
- result = mathparse.parse("fifty three point four times seven", language="ENG")
131
-
132
- self.assertEqual(result, 53.4 * 7)
133
-
134
- def test_word_decimal_simple(self):
135
- """
136
- Test: "five point two" should equal 5.2
137
- """
138
- result = mathparse.parse("five point two", language="ENG")
139
-
140
- self.assertEqual(result, 5.2)
141
-
142
- def test_word_decimal_with_addition(self):
143
- """
144
- Test: "three point five plus two point one" should equal 5.6
145
- """
146
- result = mathparse.parse("three point five plus two point one", language="ENG")
147
-
148
- self.assertEqual(result, 5.6)
149
-
150
- def test_word_decimal_with_division(self):
151
- """
152
- Test: "twenty one point six divided by four" should equal 5.4
153
- """
154
- result = mathparse.parse("twenty one point six divided by four", language="ENG")
155
-
156
- self.assertEqual(float(result), 5.4)
157
-
158
- def test_word_decimal_multi_digit_fractional(self):
159
- """
160
- Test: "ten point twenty five" should equal 10.25
161
- """
162
- result = mathparse.parse("ten point twenty five", language="ENG")
163
-
164
- self.assertEqual(result, 10.25)
165
-
166
-
167
- class ScientificNotationTestCase(TestCase):
168
-
169
- def test_positive_exponent(self):
170
- self.assertEqual(mathparse.parse('2.5e3'), 2500.0)
171
-
172
- def test_negative_exponent(self):
173
- self.assertEqual(mathparse.parse('1e-3'), 0.001)
174
-
175
- def test_explicit_plus_exponent(self):
176
- self.assertEqual(mathparse.parse('2.5e+3 * 2'), 5000.0)
177
-
178
- def test_uppercase_e(self):
179
- self.assertEqual(mathparse.parse('1.5E2'), 150.0)
180
-
181
- def test_leading_decimal_point(self):
182
- self.assertEqual(mathparse.parse('.5e1'), 5.0)
183
-
184
- def test_negative_number(self):
185
- self.assertEqual(mathparse.parse('-2.5e3 + 1'), -2499.0)
186
-
187
- def test_subtraction_after_exponent(self):
188
- self.assertEqual(mathparse.parse('1e3-2'), 998.0)
189
-
190
- def test_division(self):
191
- self.assertAlmostEqual(float(mathparse.parse('1.5e-3 / 3')), 0.0005)
192
-
193
- def test_in_parenthesis(self):
194
- self.assertEqual(mathparse.parse('(1.5e2)'), 150.0)
195
-
196
- def test_with_unary_function(self):
197
- self.assertEqual(mathparse.parse('sqrt 1e4'), 100.0)
198
-
199
- def test_with_words(self):
200
- self.assertEqual(
201
- mathparse.parse('2.5e3 plus four', language='ENG'), 2504.0
202
- )
203
-
204
- def test_constant_e_is_unaffected(self):
205
- self.assertAlmostEqual(
206
- float(mathparse.parse('e * 2')), 2 * mathwords.CONSTANTS['e']
207
- )
208
-
209
-
210
- class ModuloTestCase(TestCase):
211
-
212
- def test_modulo(self):
213
- self.assertEqual(mathparse.parse('10 % 3'), 1)
214
-
215
- def test_modulo_without_spaces(self):
216
- self.assertEqual(mathparse.parse('10%4'), 2)
217
-
218
- def test_modulo_float(self):
219
- self.assertEqual(mathparse.parse('7.5 % 2'), 1.5)
220
-
221
- def test_modulo_negative_follows_python(self):
222
- self.assertEqual(mathparse.parse('-7 % 3'), 2)
223
-
224
- def test_modulo_by_zero(self):
225
- self.assertEqual(mathparse.parse('10 % 0'), 'undefined')
226
-
227
- def test_modulo_same_precedence_as_multiplication(self):
228
- # 2 + ((10 % 4) * 3) = 2 + 6 = 8
229
- self.assertEqual(mathparse.parse('2 + 10 % 4 * 3'), 8)
230
-
231
- def test_modulo_english(self):
232
- self.assertEqual(mathparse.parse('ten mod three', language='ENG'), 1)
233
-
234
- def test_modulo_word_english(self):
235
- result = mathparse.parse('ten modulo four plus one', language='ENG')
236
- self.assertEqual(result, 3)
237
-
238
-
239
- class DoubleStarPowerTestCase(TestCase):
240
-
241
- def test_power(self):
242
- self.assertEqual(mathparse.parse('2 ** 3'), 8)
243
-
244
- def test_power_without_spaces(self):
245
- self.assertEqual(mathparse.parse('2**3'), 8)
246
-
247
- def test_power_right_associative(self):
248
- self.assertEqual(mathparse.parse('2 ** 3 ** 2'), 512)
249
-
250
- def test_power_precedence_over_multiplication(self):
251
- self.assertEqual(mathparse.parse('2 * 3 ** 2'), 18)
252
-
253
- def test_power_negative_exponent(self):
254
- self.assertEqual(mathparse.parse('2 ** -1'), 0.5)
255
-
256
- def test_power_with_parenthesis(self):
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)
1
+ from decimal import Decimal
2
+ from unittest import TestCase
3
+ from mathparse import mathparse, mathwords
4
+
5
+
6
+ class PositiveIntegerTestCase(TestCase):
7
+ def test_addition(self):
8
+ result = mathparse.parse("4 + 4")
9
+
10
+ self.assertEqual(result, 8)
11
+
12
+ def test_addition_words(self):
13
+ result = mathparse.parse("four plus four", language="ENG")
14
+
15
+ self.assertEqual(result, 8)
16
+
17
+ def test_addition_words_large(self):
18
+ result = mathparse.parse(
19
+ "four thousand two hundred one plus five hundred", language="ENG"
20
+ )
21
+
22
+ self.assertEqual(result, 4701)
23
+
24
+ def test_subtraction(self):
25
+ result = mathparse.parse("30 - 20")
26
+
27
+ self.assertEqual(result, 10)
28
+
29
+ def test_subtraction_words(self):
30
+ result = mathparse.parse("thirty minus twenty", language="ENG")
31
+
32
+ self.assertEqual(result, 10)
33
+
34
+ def test_multiplication(self):
35
+ result = mathparse.parse("9 * 9")
36
+
37
+ self.assertEqual(result, 81)
38
+
39
+ def test_multiplication_words(self):
40
+ result = mathparse.parse("nine times nine", language="ENG")
41
+
42
+ self.assertEqual(result, 81)
43
+
44
+ def test_division(self):
45
+ result = mathparse.parse("15 / 5")
46
+
47
+ self.assertEqual(result, 3)
48
+
49
+ def test_division_words(self):
50
+ result = mathparse.parse("fifteen divided by five", language="ENG")
51
+
52
+ self.assertEqual(result, 3)
53
+
54
+ def test_double_digit_multiplier_for_scale_addition(self):
55
+ result = mathparse.parse("fifty thousand plus one", language="ENG")
56
+
57
+ self.assertEqual(result, 50001)
58
+
59
+ def test_division_by_zero(self):
60
+ result = mathparse.parse("42 / 0", language="ENG")
61
+
62
+ self.assertEqual(result, "undefined")
63
+
64
+ def test_division_by_zero_words(self):
65
+ result = mathparse.parse("six divided by zero", language="ENG")
66
+
67
+ self.assertEqual(result, "undefined")
68
+
69
+ def test_division_words_large(self):
70
+ result = mathparse.parse(
71
+ "one thousand two hundred four divided by one hundred", language="ENG"
72
+ )
73
+
74
+ self.assertEqual(str(result), "12.04")
75
+
76
+ def test_operation_precedence(self):
77
+ result = mathparse.parse("2 + 3 * (4 - 2) ^ 2 / 2")
78
+
79
+ self.assertEqual(result, 8)
80
+
81
+ def test_tokens_with_extra_spaces(self):
82
+ result = mathparse.parse(" 2 + 3 * ( 4 - 2 ) ^ 2 / 2 ")
83
+
84
+ self.assertEqual(result, 8)
85
+
86
+ def test_tokens_with_no_spaces(self):
87
+ result = mathparse.parse("2+3*(4-2)^2/2")
88
+
89
+ self.assertEqual(result, 8)
90
+
91
+
92
+ class PositiveFloatTestCase(TestCase):
93
+ def test_addition(self):
94
+ result = mathparse.parse("0.6 + 0.5")
95
+
96
+ self.assertEqual(result, 1.1)
97
+
98
+ def test_subtraction(self):
99
+ result = mathparse.parse("30.1 - 29.1")
100
+
101
+ self.assertEqual(result, 1)
102
+
103
+ def test_multiplication(self):
104
+ result = mathparse.parse("0.9 * 0.9")
105
+
106
+ self.assertEqual(result, 0.81)
107
+
108
+ def test_division(self):
109
+ result = mathparse.parse("0.6 / 0.2")
110
+
111
+ self.assertEqual(result, 3)
112
+
113
+
114
+ class WordOperatorTestCase(TestCase):
115
+ def test_power_of(self):
116
+ result = mathparse.parse("2 to the power of 3", language="ENG")
117
+
118
+ self.assertEqual(result, 8)
119
+
120
+
121
+ class WordBasedDecimalTestCase(TestCase):
122
+ """
123
+ Test cases for word-based decimal numbers.
124
+ For example: "fifty three point four" should be treated as 53.4
125
+ """
126
+
127
+ def test_word_decimal_with_multiplication(self):
128
+ """
129
+ Test: "Fifty three point four times seven" should equal 53.4 * 7
130
+ """
131
+ result = mathparse.parse("fifty three point four times seven", language="ENG")
132
+
133
+ self.assertEqual(result, 53.4 * 7)
134
+
135
+ def test_word_decimal_simple(self):
136
+ """
137
+ Test: "five point two" should equal 5.2
138
+ """
139
+ result = mathparse.parse("five point two", language="ENG")
140
+
141
+ self.assertEqual(result, 5.2)
142
+
143
+ def test_word_decimal_with_addition(self):
144
+ """
145
+ Test: "three point five plus two point one" should equal 5.6
146
+ """
147
+ result = mathparse.parse("three point five plus two point one", language="ENG")
148
+
149
+ self.assertEqual(result, 5.6)
150
+
151
+ def test_word_decimal_with_division(self):
152
+ """
153
+ Test: "twenty one point six divided by four" should equal 5.4
154
+ """
155
+ result = mathparse.parse("twenty one point six divided by four", language="ENG")
156
+
157
+ self.assertEqual(float(result), 5.4)
158
+
159
+ def test_word_decimal_multi_digit_fractional(self):
160
+ """
161
+ Test: "ten point twenty five" should equal 10.25
162
+ """
163
+ result = mathparse.parse("ten point twenty five", language="ENG")
164
+
165
+ self.assertEqual(result, 10.25)
166
+
167
+
168
+ class ScientificNotationTestCase(TestCase):
169
+
170
+ def test_positive_exponent(self):
171
+ self.assertEqual(mathparse.parse('2.5e3'), 2500.0)
172
+
173
+ def test_negative_exponent(self):
174
+ self.assertEqual(mathparse.parse('1e-3'), 0.001)
175
+
176
+ def test_explicit_plus_exponent(self):
177
+ self.assertEqual(mathparse.parse('2.5e+3 * 2'), 5000.0)
178
+
179
+ def test_uppercase_e(self):
180
+ self.assertEqual(mathparse.parse('1.5E2'), 150.0)
181
+
182
+ def test_leading_decimal_point(self):
183
+ self.assertEqual(mathparse.parse('.5e1'), 5.0)
184
+
185
+ def test_negative_number(self):
186
+ self.assertEqual(mathparse.parse('-2.5e3 + 1'), -2499.0)
187
+
188
+ def test_subtraction_after_exponent(self):
189
+ self.assertEqual(mathparse.parse('1e3-2'), 998.0)
190
+
191
+ def test_division(self):
192
+ self.assertAlmostEqual(float(mathparse.parse('1.5e-3 / 3')), 0.0005)
193
+
194
+ def test_in_parenthesis(self):
195
+ self.assertEqual(mathparse.parse('(1.5e2)'), 150.0)
196
+
197
+ def test_with_unary_function(self):
198
+ self.assertEqual(mathparse.parse('sqrt 1e4'), 100.0)
199
+
200
+ def test_with_words(self):
201
+ self.assertEqual(
202
+ mathparse.parse('2.5e3 plus four', language='ENG'), 2504.0
203
+ )
204
+
205
+ def test_constant_e_is_unaffected(self):
206
+ self.assertAlmostEqual(
207
+ float(mathparse.parse('e * 2')), 2 * mathwords.CONSTANTS['e']
208
+ )
209
+
210
+
211
+ class ModuloTestCase(TestCase):
212
+
213
+ def test_modulo(self):
214
+ self.assertEqual(mathparse.parse('10 % 3'), 1)
215
+
216
+ def test_modulo_without_spaces(self):
217
+ self.assertEqual(mathparse.parse('10%4'), 2)
218
+
219
+ def test_modulo_float(self):
220
+ self.assertEqual(mathparse.parse('7.5 % 2'), 1.5)
221
+
222
+ def test_modulo_negative_follows_python(self):
223
+ self.assertEqual(mathparse.parse('-7 % 3'), 2)
224
+
225
+ def test_modulo_by_zero(self):
226
+ self.assertEqual(mathparse.parse('10 % 0'), 'undefined')
227
+
228
+ def test_modulo_same_precedence_as_multiplication(self):
229
+ # 2 + ((10 % 4) * 3) = 2 + 6 = 8
230
+ self.assertEqual(mathparse.parse('2 + 10 % 4 * 3'), 8)
231
+
232
+ def test_modulo_english(self):
233
+ self.assertEqual(mathparse.parse('ten mod three', language='ENG'), 1)
234
+
235
+ def test_modulo_word_english(self):
236
+ result = mathparse.parse('ten modulo four plus one', language='ENG')
237
+ self.assertEqual(result, 3)
238
+
239
+
240
+ class DoubleStarPowerTestCase(TestCase):
241
+
242
+ def test_power(self):
243
+ self.assertEqual(mathparse.parse('2 ** 3'), 8)
244
+
245
+ def test_power_without_spaces(self):
246
+ self.assertEqual(mathparse.parse('2**3'), 8)
247
+
248
+ def test_power_right_associative(self):
249
+ self.assertEqual(mathparse.parse('2 ** 3 ** 2'), 512)
250
+
251
+ def test_power_precedence_over_multiplication(self):
252
+ self.assertEqual(mathparse.parse('2 * 3 ** 2'), 18)
253
+
254
+ def test_power_negative_exponent(self):
255
+ self.assertEqual(mathparse.parse('2 ** -1'), 0.5)
256
+
257
+ def test_power_with_parenthesis(self):
258
+ self.assertEqual(mathparse.parse('(10 % 4) ** 2'), 4)
259
+
260
+
261
+ class ConstantDivisionTestCase(TestCase):
262
+
263
+ def test_constant_numerator(self):
264
+ result = mathparse.parse('pi / 2')
265
+ self.assertAlmostEqual(float(result), mathwords.CONSTANTS['pi'] / 2)
266
+
267
+ def test_constant_denominator(self):
268
+ result = mathparse.parse('2 / pi')
269
+ self.assertAlmostEqual(float(result), 2 / mathwords.CONSTANTS['pi'])
270
+
271
+ def test_constant_modulo(self):
272
+ result = mathparse.parse('10 % pi')
273
+ self.assertAlmostEqual(float(result), 10 % mathwords.CONSTANTS['pi'])
274
+
275
+
276
+ class ConstantResultTestCase(TestCase):
277
+
278
+ def test_pi(self):
279
+ self.assertEqual(mathparse.parse('pi'), mathwords.CONSTANTS['pi'])
280
+
281
+ def test_e(self):
282
+ self.assertEqual(mathparse.parse('e'), mathwords.CONSTANTS['e'])
283
+
284
+ def test_constant_in_parenthesis(self):
285
+ self.assertEqual(mathparse.parse('(pi)'), mathwords.CONSTANTS['pi'])
286
+
287
+ def test_negative_constant(self):
288
+ self.assertEqual(mathparse.parse('-pi'), -mathwords.CONSTANTS['pi'])
289
+
290
+ def test_negative_constant_after_operator(self):
291
+ result = mathparse.parse('2 * -pi')
292
+ self.assertEqual(result, -2 * mathwords.CONSTANTS['pi'])
293
+
294
+ def test_negative_function(self):
295
+ self.assertEqual(mathparse.parse('-sqrt 4'), -2.0)
296
+
297
+ def test_hyphenated_number_word_is_unaffected(self):
298
+ result = mathparse.parse('twenty-one plus one', language='ENG')
299
+ self.assertEqual(result, 22)
300
+
301
+
302
+ class MixedDecimalFloatTestCase(TestCase):
303
+ """
304
+ Division returns a Decimal, which must still combine with floats.
305
+ """
306
+
307
+ def test_division_minus_scientific_notation(self):
308
+ result = mathparse.parse("abs(170e6/32 - 8e6)/8e6")
309
+
310
+ self.assertEqual(result, Decimal("0.3359375"))
311
+
312
+ def test_division_plus_float(self):
313
+ result = mathparse.parse("10 / 4 + 0.5")
314
+
315
+ self.assertEqual(result, 3)
316
+
317
+ def test_division_minus_float(self):
318
+ result = mathparse.parse("10 / 4 - 1.5")
319
+
320
+ self.assertEqual(result, 1)
321
+
322
+ def test_float_minus_division(self):
323
+ result = mathparse.parse("1.5 - 10 / 4")
324
+
325
+ self.assertEqual(result, -1)
326
+
327
+ def test_division_times_scientific_notation(self):
328
+ result = mathparse.parse("10 / 4 * 2e1")
329
+
330
+ self.assertEqual(result, 50)
331
+
332
+ def test_division_modulo_float(self):
333
+ result = mathparse.parse("10 / 4 % 1.5")
334
+
335
+ self.assertEqual(result, 1)
336
+
337
+ def test_division_power_float(self):
338
+ result = mathparse.parse("(10 / 4) ^ 2e0")
339
+
340
+ self.assertEqual(result, Decimal("6.25"))
341
+
342
+ def test_division_compared_to_float(self):
343
+ result = mathparse.parse("10 / 4 == 2.5e0")
344
+
345
+ self.assertTrue(result)