mathparse 0.2.5__tar.gz → 0.2.6__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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: mathparse
3
- Version: 0.2.5
3
+ Version: 0.2.6
4
4
  Summary: mathparse is 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.5'
5
+ __version__ = '0.2.6'
@@ -18,11 +18,13 @@ def is_int(string: str) -> bool:
18
18
  """
19
19
  Return true if string is an integer.
20
20
  """
21
- try:
22
- int(string)
23
- return True
24
- except ValueError:
25
- return False
21
+ # Allow leading minus sign
22
+ if string[0] == '-':
23
+ # Must have at least one digit after the minus
24
+ return len(string) > 1 and string[1:].isdigit()
25
+ else:
26
+ # Must be all digits
27
+ return string.isdigit()
26
28
 
27
29
 
28
30
  def is_float(string: str) -> bool:
@@ -79,6 +81,27 @@ def is_word(word: str, language: str) -> bool:
79
81
  return word in words
80
82
 
81
83
 
84
+ def to_number(val) -> Union[int, float, str, Decimal]:
85
+ """
86
+ Convert a string to an int or float if possible.
87
+ """
88
+ # If already a number (int, float, Decimal), return as-is
89
+ if isinstance(val, (int, float, Decimal)):
90
+ return val
91
+
92
+ # Check if it's a constant and convert
93
+ if is_constant(val):
94
+ return mathwords.CONSTANTS[val]
95
+
96
+ # Otherwise, try to convert string to number
97
+ if is_int(val):
98
+ return int(val)
99
+ elif is_float(val):
100
+ return float(val)
101
+
102
+ return val
103
+
104
+
82
105
  def create_unicode_word_boundary_pattern(word: str) -> str:
83
106
  """
84
107
  Create a regex pattern with Unicode-aware word boundaries.
@@ -459,11 +482,11 @@ def to_postfix(tokens: list) -> list:
459
482
 
460
483
  for token in tokens:
461
484
  if is_int(token):
462
- postfix.append(int(token))
485
+ postfix.append(token)
463
486
  elif is_float(token):
464
- postfix.append(float(token))
487
+ postfix.append(token)
465
488
  elif token in mathwords.CONSTANTS:
466
- postfix.append(mathwords.CONSTANTS[token])
489
+ postfix.append(token)
467
490
  elif is_unary(token):
468
491
  opstack.append(token)
469
492
  elif token == '(':
@@ -516,6 +539,8 @@ def evaluate_postfix(tokens: list) -> Union[int, float, str, Decimal]:
516
539
  stack.append(token)
517
540
  elif is_unary(token):
518
541
  a = stack.pop()
542
+ # Convert token (string) to number for unary function evaluation
543
+ a = to_number(a)
519
544
  total = mathwords.UNARY_FUNCTIONS[token](a)
520
545
  elif len(stack) == 1:
521
546
  raise PostfixTokenEvaluationException(
@@ -526,14 +551,15 @@ def evaluate_postfix(tokens: list) -> Union[int, float, str, Decimal]:
526
551
  elif len(stack) > 1:
527
552
  b = stack.pop()
528
553
  a = stack.pop()
554
+
529
555
  if token == '+':
530
- total = a + b
556
+ total = to_number(a) + to_number(b)
531
557
  elif token == '-':
532
- total = a - b
558
+ total = to_number(a) - to_number(b)
533
559
  elif token == '*':
534
- total = a * b
560
+ total = to_number(a) * to_number(b)
535
561
  elif token == '^':
536
- total = a ** b
562
+ total = to_number(a) ** to_number(b)
537
563
  elif token == '/':
538
564
  if Decimal(str(b)) == 0:
539
565
  total = 'undefined'
@@ -543,19 +569,33 @@ def evaluate_postfix(tokens: list) -> Union[int, float, str, Decimal]:
543
569
  # Treat decimal points as a binary operator that combines the
544
570
  # integer and fractional part of two numbers
545
571
  # Example: 53 . 25 = 53.25, -3 . 5 = -3.5
546
- if b == 0:
547
- total = Decimal(a)
572
+
573
+ # Convert b to number
574
+ numeric_b = to_number(b)
575
+
576
+ if numeric_b == 0:
577
+ # Convert a to number
578
+ numeric_a = to_number(a)
579
+ total = Decimal(numeric_a)
548
580
  else:
549
- # Count the digits in b to determine the divisor
550
- digits = len(str(int(b)))
581
+ # Check if 'a' has a negative sign (handles -0 case)
582
+ is_negative = str(a).startswith('-')
583
+
584
+ # Convert a to number for calculation
585
+ numeric_a = to_number(a)
586
+
587
+ # Count the digits in the original string b to preserve
588
+ # leading zeros (e.g., "01" has 2 digits, not 1)
589
+ digits = len(str(b))
551
590
  divisor = 10 ** digits
552
- fractional_part = b / divisor
553
- # Handle negative numbers correctly: -3 . 5 should be -3.5,
554
- # not -2.5
555
- if a < 0:
556
- total = a - fractional_part
591
+ fractional_part = numeric_b / divisor
592
+
593
+ # Handle negatives: -3 . 5 = -3.5, not -2.5
594
+ # Also -0 . 5 = -0.5 (check string since -0 == 0)
595
+ if is_negative:
596
+ total = numeric_a - fractional_part
557
597
  else:
558
- total = a + fractional_part
598
+ total = numeric_a + fractional_part
559
599
  else:
560
600
  raise PostfixTokenEvaluationException(
561
601
  'Unknown token "{}"'.format(token)
@@ -570,7 +610,16 @@ def evaluate_postfix(tokens: list) -> Union[int, float, str, Decimal]:
570
610
  'The postfix expression resulted in an empty stack'
571
611
  )
572
612
 
573
- return stack.pop()
613
+ result = stack.pop()
614
+
615
+ # Convert final result from string to number if needed
616
+ if isinstance(result, str):
617
+ if is_int(result):
618
+ result = int(result)
619
+ elif is_float(result):
620
+ result = float(result)
621
+
622
+ return result
574
623
 
575
624
 
576
625
  def tokenize(string: str, language: str = None, escape: str = '___') -> list:
@@ -822,4 +871,10 @@ def extract_expression(dirty_string: str, language: str) -> str:
822
871
  else:
823
872
  end_index -= 1
824
873
 
825
- return ' '.join(tokens[start_index:end_index])
874
+ result = ' '.join(tokens[start_index:end_index])
875
+
876
+ # Remove spaces around decimal points for cleaner output
877
+ # Replace " . " with "." to convert "-100 . 5" to "-100.5"
878
+ result = result.replace(' . ', '.')
879
+
880
+ return result
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: mathparse
3
- Version: 0.2.5
3
+ Version: 0.2.6
4
4
  Summary: mathparse is a library for solving mathematical equations contained in strings
5
5
  Author: Gunther Cox
6
6
  License-Expression: MIT
@@ -231,6 +231,15 @@ class ExtractExpressionNegativeTestCase(TestCase):
231
231
  result = mathparse.extract_expression('5 - 3', language='ENG')
232
232
  self.assertEqual(result, '5 - 3')
233
233
 
234
+ def test_extract_negative_decimal(self):
235
+ """
236
+ Test: Extract leading negative decimal from sentence
237
+ """
238
+ result = mathparse.extract_expression(
239
+ 'What is -100.5 * 20?', language='ENG'
240
+ )
241
+ self.assertEqual(result, '-100.5 * 20')
242
+
234
243
  def test_extract_negative_in_parentheses_with_words(self):
235
244
  """
236
245
  Test: Extract expression with negative in parentheses from sentence
@@ -241,3 +250,148 @@ class ExtractExpressionNegativeTestCase(TestCase):
241
250
  # NOTE: Spaces are currently added, but ideally these will be removed
242
251
  # in the future
243
252
  self.assertEqual(result, '( -3 ) + 5')
253
+
254
+
255
+ class NegativeDecimalsLessThanOneTestCase(TestCase):
256
+ """
257
+ Test cases for negative decimal numbers between -1 and 0.
258
+
259
+ This addresses a bug where negative decimals less than 1
260
+ (e.g., -0.2, -0.5) were losing their negative sign during parsing.
261
+ The issue was caused by Python's -0 == 0 equality, where int('-0')
262
+ returns 0, losing sign information.
263
+ """
264
+
265
+ def test_negative_zero_point_two(self):
266
+ """
267
+ Test: -0.2 should equal -0.2
268
+ """
269
+ result = mathparse.parse('-0.2')
270
+ self.assertEqual(result, -0.2)
271
+
272
+ def test_negative_zero_point_five(self):
273
+ """
274
+ Test: -0.5 should equal -0.5
275
+ """
276
+ result = mathparse.parse('-0.5')
277
+ self.assertEqual(result, -0.5)
278
+
279
+ def test_negative_zero_point_nine(self):
280
+ """
281
+ Test: -0.9 should equal -0.9
282
+ """
283
+ result = mathparse.parse('-0.9')
284
+ self.assertEqual(result, -0.9)
285
+
286
+ def test_negative_zero_point_one(self):
287
+ """
288
+ Test: -0.1 should equal -0.1
289
+ """
290
+ result = mathparse.parse('-0.1')
291
+ self.assertEqual(result, -0.1)
292
+
293
+ def test_negative_zero_point_ninety_nine(self):
294
+ """
295
+ Test: -0.99 should equal -0.99"""
296
+ result = mathparse.parse('-0.99')
297
+ self.assertEqual(result, -0.99)
298
+
299
+ def test_negative_zero_point_zero_one(self):
300
+ """
301
+ Test: -0.01 should equal -0.01
302
+ """
303
+ result = mathparse.parse('-0.01')
304
+ self.assertEqual(result, -0.01)
305
+
306
+ def test_negative_zero_point_nine_nine_nine(self):
307
+ """
308
+ Test: -0.999 should equal -0.999
309
+ """
310
+ result = mathparse.parse('-0.999')
311
+ self.assertEqual(result, -0.999)
312
+
313
+ def test_negative_decimal_in_addition(self):
314
+ """
315
+ Test: -0.5 + 1 should equal 0.5
316
+ """
317
+ result = mathparse.parse('-0.5 + 1')
318
+ self.assertEqual(result, 0.5)
319
+
320
+ def test_negative_decimal_in_subtraction(self):
321
+ """
322
+ Test: 2 - -0.5 should equal 2.5
323
+ """
324
+ result = mathparse.parse('2 - -0.5')
325
+ self.assertEqual(result, 2.5)
326
+
327
+ def test_negative_decimal_in_multiplication(self):
328
+ """
329
+ Test: -0.5 * 4 should equal -2.0
330
+ """
331
+ result = mathparse.parse('-0.5 * 4')
332
+ self.assertEqual(result, -2.0)
333
+
334
+ def test_negative_decimal_in_division(self):
335
+ """
336
+ Test: -0.8 / 2 should equal -0.4
337
+ """
338
+ result = mathparse.parse('-0.8 / 2')
339
+ self.assertEqual(float(result), -0.4)
340
+
341
+ def test_multiple_negative_decimals(self):
342
+ """
343
+ Test: -0.3 + -0.2 should equal -0.5
344
+ """
345
+ result = mathparse.parse('-0.3 + -0.2')
346
+ self.assertAlmostEqual(result, -0.5, places=10)
347
+
348
+ def test_negative_decimal_with_parentheses(self):
349
+ """
350
+ Test: (-0.5) should equal -0.5
351
+ """
352
+ result = mathparse.parse('(-0.5)')
353
+ self.assertEqual(result, -0.5)
354
+
355
+ def test_negative_decimal_in_complex_expression(self):
356
+ """
357
+ Test: (-0.5 + 1) * 2 should equal 1.0
358
+ """
359
+ result = mathparse.parse('(-0.5 + 1) * 2')
360
+ self.assertEqual(result, 1.0)
361
+
362
+ def test_positive_decimals_still_work(self):
363
+ """
364
+ Test: 0.5 should equal 0.5
365
+ """
366
+ result = mathparse.parse('0.5')
367
+ self.assertEqual(result, 0.5)
368
+
369
+ def test_negative_integers_still_work(self):
370
+ """
371
+ Test: -5 should equal -5
372
+ """
373
+ result = mathparse.parse('-5')
374
+ self.assertEqual(result, -5)
375
+
376
+ def test_negative_decimals_greater_than_one_still_work(self):
377
+ """
378
+ Test: -1.5 should equal -1.5
379
+ """
380
+ result = mathparse.parse('-1.5')
381
+ self.assertEqual(result, -1.5)
382
+
383
+ def test_temperature_conversion_use_case(self):
384
+ """
385
+ -0.2 Celsius to Fahrenheit formula: (-0.2 * 9/5) + 32 = 31.64
386
+ (Example calculation)
387
+ """
388
+ result = mathparse.parse('-0.2 * 9 / 5 + 32')
389
+ self.assertAlmostEqual(float(result), 31.64, places=2)
390
+
391
+ def test_financial_calculation_use_case(self):
392
+ """
393
+ Balance: $100, transaction: -$0.25, expected: $99.75
394
+ (Example calculation)
395
+ """
396
+ result = mathparse.parse('100 + -0.25')
397
+ self.assertEqual(result, 99.75)
@@ -11,12 +11,18 @@ class BooleanChecksTestCase(TestCase):
11
11
  def test_is_not_integer(self):
12
12
  self.assertFalse(mathparse.is_int('42.2'))
13
13
 
14
+ def test_is_not_integer_negative(self):
15
+ self.assertFalse(mathparse.is_int('-42.2'))
16
+
14
17
  def test_is_float(self):
15
18
  self.assertTrue(mathparse.is_float('0.5'))
16
19
 
17
20
  def test_is_not_float(self):
18
21
  self.assertFalse(mathparse.is_float('5'))
19
22
 
23
+ def test_is_not_float_negative(self):
24
+ self.assertTrue(mathparse.is_float('-0.5'))
25
+
20
26
  def test_is_constant(self):
21
27
  self.assertTrue(mathparse.is_constant('pi'))
22
28
 
File without changes
File without changes
File without changes
File without changes