mathjson-solver 2.2.0__py3-none-any.whl → 2.2.1__py3-none-any.whl

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,9 +1,21 @@
1
1
  import numbers
2
+ import sys
2
3
  from typing import Union, Any
3
4
  from functools import reduce
5
+ from fractions import Fraction
4
6
  import math
5
7
  from copy import deepcopy
6
- from statistics import median, variance, stdev
8
+ from statistics import (
9
+ median,
10
+ variance,
11
+ stdev,
12
+ pvariance,
13
+ pstdev,
14
+ mode,
15
+ quantiles,
16
+ covariance,
17
+ correlation,
18
+ )
7
19
  import datetime
8
20
 
9
21
  NUMPY_AVAILABLE = False
@@ -14,6 +26,26 @@ try:
14
26
  except ImportError:
15
27
  pass
16
28
 
29
+ RE2_AVAILABLE = False
30
+ try:
31
+ import re2
32
+
33
+ RE2_AVAILABLE = True
34
+ # No public "re2.Pattern" name is exported; derive the actual
35
+ # compiled-pattern type at import time rather than hardcoding
36
+ # re2's internal class path.
37
+ _RE2_PATTERN_TYPE = type(re2.compile(""))
38
+ except ImportError:
39
+ _RE2_PATTERN_TYPE = None
40
+
41
+ # Hard cap on the result length of string operations whose size is
42
+ # otherwise controlled directly by a user-supplied count/length
43
+ # argument (StringRepeat, PadStart, PadEnd) - closes the same
44
+ # memory/time exhaustion shape that Loop/Random/arbitrary-size Repeat
45
+ # are excluded for elsewhere in this solver, but here it's cheaply and
46
+ # exactly bounded by a single length check before any allocation.
47
+ _MAX_STRING_REPEAT_LENGTH = 100_000
48
+
17
49
  NoneType = type(None)
18
50
 
19
51
 
@@ -325,6 +357,15 @@ def create_mathjson_solver(solver_parameters, legacy_v1=False):
325
357
  # c = deepcopy(kwargs.get("c", {}))
326
358
  if isinstance(s, numbers.Number):
327
359
  return s
360
+ # CortexJS represents the boolean literals as the bare symbols
361
+ # "True" and "False" (as opposed to native JSON `true`/`false`,
362
+ # which already arrive here as Python bool - itself a `numbers.Number`
363
+ # subtype, so it's handled by the check above). Resolve them to
364
+ # actual booleans unconditionally, the same way numeric literals
365
+ # are resolved above, so they can't be shadowed by a same-named
366
+ # solver parameter or local variable.
367
+ if s == "True" or s == "False":
368
+ return s == "True"
328
369
  if isinstance(s, list):
329
370
 
330
371
  def Arr(s):
@@ -472,6 +513,12 @@ def create_mathjson_solver(solver_parameters, legacy_v1=False):
472
513
  def First(s):
473
514
  return _arr_vals(s)[0]
474
515
 
516
+ def Second(s):
517
+ return _arr_vals(s)[1]
518
+
519
+ def Third(s):
520
+ return _arr_vals(s)[2]
521
+
475
522
  def Last(s):
476
523
  return _arr_vals(s)[-1]
477
524
 
@@ -554,6 +601,465 @@ def create_mathjson_solver(solver_parameters, legacy_v1=False):
554
601
  else:
555
602
  return vals[idx]
556
603
 
604
+ def Take(s):
605
+ """
606
+ ["Take", array, n]
607
+ First `n` elements if n >= 0; last `n` elements if n < 0.
608
+ Distinct from `Slice`, which takes an explicit [start, end)
609
+ range instead of a count.
610
+ """
611
+ vals = _arr_vals(s)
612
+ n = int(f(s[2], c))
613
+ if n >= 0:
614
+ return ["Array"] + vals[:n]
615
+ return ["Array"] + vals[n:]
616
+
617
+ def Drop(s):
618
+ """
619
+ ["Drop", array, n]
620
+ All elements except the first `n` if n >= 0; except the
621
+ last `n` if n < 0.
622
+ """
623
+ vals = _arr_vals(s)
624
+ n = int(f(s[2], c))
625
+ if n >= 0:
626
+ return ["Array"] + vals[n:]
627
+ return ["Array"] + vals[:n]
628
+
629
+ def TakeWhile(s):
630
+ """
631
+ ["TakeWhile", array, predicate]
632
+ Elements from the start, up to (excluding) the first one
633
+ for which `predicate` is false.
634
+ """
635
+ result = []
636
+ for v in _arr_vals(s):
637
+ if not _apply_fn(s[2], [v]):
638
+ break
639
+ result.append(v)
640
+ return ["Array"] + result
641
+
642
+ def DropWhile(s):
643
+ """
644
+ ["DropWhile", array, predicate]
645
+ Remaining elements from (and including) the first one for
646
+ which `predicate` is false.
647
+ """
648
+ vals = _arr_vals(s)
649
+ i = 0
650
+ while i < len(vals) and _apply_fn(s[2], [vals[i]]):
651
+ i += 1
652
+ return ["Array"] + vals[i:]
653
+
654
+ def Contains(s):
655
+ """
656
+ ["Contains", array, value]
657
+ Whether `value` occurs in `array`. CortexJS argument order
658
+ (collection first) - the existing `In` takes them the
659
+ other way round (`["In", value, collection]`).
660
+ """
661
+ return f(s[2], c) in _arr_vals(s)
662
+
663
+ def IndexOf(s):
664
+ """
665
+ ["IndexOf", array, value]
666
+ 1-indexed position of the first occurrence of `value`, or
667
+ None if it doesn't occur.
668
+ """
669
+ vals = _arr_vals(s)
670
+ value = f(s[2], c)
671
+ try:
672
+ return vals.index(value) + 1
673
+ except ValueError:
674
+ return None
675
+
676
+ def IndexWhere(s):
677
+ """
678
+ ["IndexWhere", array, predicate]
679
+ 1-indexed position of the first element for which
680
+ `predicate` is true, or None if none match.
681
+ """
682
+ for i, v in enumerate(_arr_vals(s)):
683
+ if _apply_fn(s[2], [v]):
684
+ return i + 1
685
+ return None
686
+
687
+ def Find(s):
688
+ """
689
+ ["Find", array, predicate]
690
+ The first element for which `predicate` is true, or None
691
+ if none match.
692
+ """
693
+ for v in _arr_vals(s):
694
+ if _apply_fn(s[2], [v]):
695
+ return v
696
+ return None
697
+
698
+ def CountIf(s):
699
+ """
700
+ ["CountIf", array, predicate]
701
+ Count of elements for which `predicate` is true.
702
+ """
703
+ return sum(1 for v in _arr_vals(s) if _apply_fn(s[2], [v]))
704
+
705
+ def Position(s):
706
+ """
707
+ ["Position", array, predicate]
708
+ Array of the 1-indexed positions of every element for
709
+ which `predicate` is true.
710
+ """
711
+ return ["Array"] + [
712
+ i + 1
713
+ for i, v in enumerate(_arr_vals(s))
714
+ if _apply_fn(s[2], [v])
715
+ ]
716
+
717
+ def RotateLeft(s):
718
+ """
719
+ ["RotateLeft", array, n]
720
+ Circularly shifts `array` left by `n` positions.
721
+ """
722
+ vals = _arr_vals(s)
723
+ if not vals:
724
+ return ["Array"]
725
+ n = int(f(s[2], c)) % len(vals)
726
+ return ["Array"] + vals[n:] + vals[:n]
727
+
728
+ def RotateRight(s):
729
+ """
730
+ ["RotateRight", array, n]
731
+ Circularly shifts `array` right by `n` positions.
732
+ """
733
+ vals = _arr_vals(s)
734
+ if not vals:
735
+ return ["Array"]
736
+ n = int(f(s[2], c)) % len(vals)
737
+ if n == 0:
738
+ return ["Array"] + vals
739
+ return ["Array"] + vals[-n:] + vals[:-n]
740
+
741
+ def MaxBy(s):
742
+ """
743
+ ["MaxBy", array, function]
744
+ The element of `array` for which `function(element)` is
745
+ largest.
746
+ """
747
+ return max(_arr_vals(s), key=lambda v: _apply_fn(s[2], [v]))
748
+
749
+ def MinBy(s):
750
+ """
751
+ ["MinBy", array, function]
752
+ The element of `array` for which `function(element)` is
753
+ smallest.
754
+ """
755
+ return min(_arr_vals(s), key=lambda v: _apply_fn(s[2], [v]))
756
+
757
+ def ArgMax(s):
758
+ """
759
+ ["ArgMax", array]
760
+ 1-indexed position of the largest element.
761
+ """
762
+ vals = _arr_vals(s)
763
+ return max(range(len(vals)), key=lambda i: vals[i]) + 1
764
+
765
+ def ArgMin(s):
766
+ """
767
+ ["ArgMin", array]
768
+ 1-indexed position of the smallest element.
769
+ """
770
+ vals = _arr_vals(s)
771
+ return min(range(len(vals)), key=lambda i: vals[i]) + 1
772
+
773
+ def Ordering(s):
774
+ """
775
+ ["Ordering", array]
776
+ Array of the 1-indexed positions that would put `array`
777
+ in ascending order.
778
+ """
779
+ vals = _arr_vals(s)
780
+ return ["Array"] + [
781
+ i + 1 for i in sorted(range(len(vals)), key=lambda i: vals[i])
782
+ ]
783
+
784
+ def FlatMap(s):
785
+ """
786
+ ["FlatMap", array, function]
787
+ Applies `function` to each element (as with `Map`) and
788
+ flattens one level of the results - each result that is
789
+ itself an array is spliced in, others are kept as-is -
790
+ into a single array.
791
+ """
792
+ result = ["Array"]
793
+ for v in _arr_vals(s):
794
+ mapped = _apply_fn(s[2], [v])
795
+ if isinstance(mapped, list) and mapped and mapped[0] == "Array":
796
+ result += mapped[1:]
797
+ else:
798
+ result.append(mapped)
799
+ return result
800
+
801
+ def Scan(s):
802
+ """
803
+ ["Scan", array, function] or ["Scan", array, function, initial]
804
+ Like `Reduce`'s CortexJS form (`function` applied as
805
+ `function(accumulator, current)`), but returns an array of
806
+ every intermediate accumulator value, including the seed,
807
+ instead of just the final one.
808
+ """
809
+ vals = _arr_vals(s)
810
+ fn_expr = s[2]
811
+ if len(s) == 4:
812
+ acc = f(s[3], c)
813
+ remaining = vals
814
+ else:
815
+ if not vals:
816
+ raise ValueError(
817
+ "'Scan' on an empty collection requires an initial value."
818
+ )
819
+ acc = vals[0]
820
+ remaining = vals[1:]
821
+ result = ["Array", acc]
822
+ for v in remaining:
823
+ acc = _apply_fn(fn_expr, [acc, v])
824
+ result.append(acc)
825
+ return result
826
+
827
+ def Differences(s):
828
+ """
829
+ ["Differences", array]
830
+ Array of successive differences: element[i+1] - element[i].
831
+ """
832
+ vals = _arr_vals(s)
833
+ return ["Array"] + [b - a for a, b in zip(vals, vals[1:])]
834
+
835
+ def Fold(s):
836
+ """
837
+ ["Fold", function, array] or ["Fold", function, array, initial]
838
+ The function-first form of `Reduce`'s CortexJS calling
839
+ convention (`["Reduce", array, function, ...]`) - same
840
+ behaviour, arguments swapped.
841
+ """
842
+ if len(s) == 3:
843
+ return Reduce(["Reduce", s[2], s[1]])
844
+ return Reduce(["Reduce", s[2], s[1], s[3]])
845
+
846
+ def Dedup(s):
847
+ """
848
+ ["Dedup", array]
849
+ Removes only *consecutive* duplicate elements - distinct
850
+ from `Unique`, which removes every duplicate regardless of
851
+ position.
852
+ """
853
+ result = []
854
+ for v in _arr_vals(s):
855
+ if not result or result[-1] != v:
856
+ result.append(v)
857
+ return ["Array"] + result
858
+
859
+ def Insert(s):
860
+ """
861
+ ["Insert", array, index, value]
862
+ Inserts `value` at the 1-indexed `index` (CortexJS
863
+ convention, matching `At`); negative indexes count from
864
+ the end.
865
+ """
866
+ vals = _arr_vals(s)
867
+ idx = int(f(s[2], c))
868
+ value = f(s[3], c)
869
+ vals.insert(idx - 1 if idx > 0 else idx, value)
870
+ return ["Array"] + vals
871
+
872
+ def DeleteAt(s):
873
+ """
874
+ ["DeleteAt", array, index]
875
+ Removes the element at the 1-indexed `index`; negative
876
+ indexes count from the end.
877
+ """
878
+ vals = _arr_vals(s)
879
+ idx = int(f(s[2], c))
880
+ del vals[idx - 1 if idx > 0 else idx]
881
+ return ["Array"] + vals
882
+
883
+ def ReplaceAt(s):
884
+ """
885
+ ["ReplaceAt", array, index, value]
886
+ Replaces the element at the 1-indexed `index` with
887
+ `value`; negative indexes count from the end.
888
+ """
889
+ vals = _arr_vals(s)
890
+ idx = int(f(s[2], c))
891
+ value = f(s[3], c)
892
+ vals[idx - 1 if idx > 0 else idx] = value
893
+ return ["Array"] + vals
894
+
895
+ def Partition(s):
896
+ """
897
+ ["Partition", array, size]
898
+ Splits `array` into consecutive chunks of length `size`
899
+ (the last chunk may be shorter). Distinct from `Chunk`,
900
+ which instead takes the number of groups to split into.
901
+ """
902
+ vals = _arr_vals(s)
903
+ size = int(f(s[2], c))
904
+ if size <= 0:
905
+ raise ValueError("'Partition' size must be a positive integer.")
906
+ return ["Array"] + [
907
+ ["Array"] + vals[i : i + size] for i in range(0, len(vals), size)
908
+ ]
909
+
910
+ def Chunk(s):
911
+ """
912
+ ["Chunk", array, n]
913
+ Splits `array` into `n` roughly equal-sized consecutive
914
+ groups.
915
+ """
916
+ vals = _arr_vals(s)
917
+ n = int(f(s[2], c))
918
+ if n <= 0:
919
+ raise ValueError("'Chunk' group count must be a positive integer.")
920
+ base, extra = divmod(len(vals), n)
921
+ result, start = [], 0
922
+ for i in range(n):
923
+ size = base + (1 if i < extra else 0)
924
+ result.append(["Array"] + vals[start : start + size])
925
+ start += size
926
+ return ["Array"] + result
927
+
928
+ def GroupBy(s):
929
+ """
930
+ ["GroupBy", array, function]
931
+ Groups elements of `array` by `function(element)`, in
932
+ order of first appearance of each key. Returns an array of
933
+ [key, group] pairs - there's no dedicated `Dictionary`
934
+ type in this solver.
935
+ """
936
+ order = []
937
+ groups = {}
938
+ for v in _arr_vals(s):
939
+ k = _apply_fn(s[2], [v])
940
+ hk = tuple(k) if isinstance(k, list) else k
941
+ if hk not in groups:
942
+ order.append((hk, k))
943
+ groups[hk] = []
944
+ groups[hk].append(v)
945
+ return ["Array"] + [
946
+ ["Array", k, ["Array"] + groups[hk]] for hk, k in order
947
+ ]
948
+
949
+ def ChunkBy(s):
950
+ """
951
+ ["ChunkBy", array, function]
952
+ Splits `array` into consecutive runs sharing the same
953
+ `function(element)` key - unlike `GroupBy`, runs are not
954
+ merged across non-adjacent occurrences of the same key.
955
+ """
956
+ vals = _arr_vals(s)
957
+ if not vals:
958
+ return ["Array"]
959
+ result = []
960
+ current = [vals[0]]
961
+ current_key = _apply_fn(s[2], [vals[0]])
962
+ for v in vals[1:]:
963
+ k = _apply_fn(s[2], [v])
964
+ if k == current_key:
965
+ current.append(v)
966
+ else:
967
+ result.append(["Array"] + current)
968
+ current, current_key = [v], k
969
+ result.append(["Array"] + current)
970
+ return ["Array"] + result
971
+
972
+ def Tally(s):
973
+ """
974
+ ["Tally", array]
975
+ Counts occurrences of each distinct element, in order of
976
+ first appearance. Returns an array of [value, count]
977
+ pairs.
978
+ """
979
+ order = []
980
+ counts = {}
981
+ for v in _arr_vals(s):
982
+ hv = tuple(v) if isinstance(v, list) else v
983
+ if hv not in counts:
984
+ order.append((hv, v))
985
+ counts[hv] = 0
986
+ counts[hv] += 1
987
+ return ["Array"] + [["Array", v, counts[hv]] for hv, v in order]
988
+
989
+ def _arr_vals_of(expr):
990
+ """
991
+ Like `_arr_vals`, but for an arbitrary expression instead
992
+ of assuming the array is at `s[1]` - needed by the
993
+ variadic set operations below.
994
+ """
995
+ lst = f(expr, c)
996
+ if not (isinstance(lst, list) and lst[0] == "Array"):
997
+ raise ValueError("Parameter must be an array.")
998
+ return [f(x, c) for x in lst[1:]]
999
+
1000
+ def Union(s):
1001
+ """
1002
+ ["Union", array1, array2, ...]
1003
+ Distinct elements appearing in any of the given arrays, in
1004
+ order of first appearance across the arguments
1005
+ (left to right). Arrays stand in for CortexJS's `Set`
1006
+ here - there's no dedicated set type in this solver.
1007
+ """
1008
+ result = []
1009
+ for arg in s[1:]:
1010
+ for v in _arr_vals_of(arg):
1011
+ if v not in result:
1012
+ result.append(v)
1013
+ return ["Array"] + result
1014
+
1015
+ def Intersection(s):
1016
+ """
1017
+ ["Intersection", array1, array2, ...]
1018
+ Distinct elements common to every given array, in the
1019
+ order they first appear in `array1`.
1020
+ """
1021
+ arrays = [_arr_vals_of(arg) for arg in s[1:]]
1022
+ if not arrays:
1023
+ return ["Array"]
1024
+ result = []
1025
+ for v in arrays[0]:
1026
+ if v not in result and all(v in arr for arr in arrays[1:]):
1027
+ result.append(v)
1028
+ return ["Array"] + result
1029
+
1030
+ def SetMinus(s):
1031
+ """
1032
+ ["SetMinus", array1, array2]
1033
+ Distinct elements of `array1` that don't occur in
1034
+ `array2`.
1035
+ """
1036
+ a = _arr_vals_of(s[1])
1037
+ b = _arr_vals_of(s[2])
1038
+ result = []
1039
+ for v in a:
1040
+ if v not in b and v not in result:
1041
+ result.append(v)
1042
+ return ["Array"] + result
1043
+
1044
+ def SymmetricDifference(s):
1045
+ """
1046
+ ["SymmetricDifference", array1, array2]
1047
+ Distinct elements that occur in exactly one of
1048
+ `array1`/`array2`: `array1`'s exclusive elements first
1049
+ (in `array1`'s order), then `array2`'s (in `array2`'s
1050
+ order).
1051
+ """
1052
+ a = _arr_vals_of(s[1])
1053
+ b = _arr_vals_of(s[2])
1054
+ result = []
1055
+ for v in a:
1056
+ if v not in b and v not in result:
1057
+ result.append(v)
1058
+ for v in b:
1059
+ if v not in a and v not in result:
1060
+ result.append(v)
1061
+ return ["Array"] + result
1062
+
557
1063
  def IsPrime(s):
558
1064
  return _is_prime(f(s[1], c))
559
1065
 
@@ -563,6 +1069,53 @@ def create_mathjson_solver(solver_parameters, legacy_v1=False):
563
1069
  def StandardDeviation(s):
564
1070
  return stdev(_arr_vals(s))
565
1071
 
1072
+ def PopulationVariance(s):
1073
+ return pvariance(_arr_vals(s))
1074
+
1075
+ def PopulationStandardDeviation(s):
1076
+ return pstdev(_arr_vals(s))
1077
+
1078
+ def Mode(s):
1079
+ """
1080
+ ["Mode", array]
1081
+ The most frequently occurring value. Ties go to whichever
1082
+ value appears first in `array` (matching Python's
1083
+ `statistics.mode`).
1084
+ """
1085
+ return mode(_arr_vals(s))
1086
+
1087
+ def Quartiles(s):
1088
+ """
1089
+ ["Quartiles", array]
1090
+ The three points (Q1, Q2/median, Q3) that divide `array`
1091
+ into four equal-sized groups, using
1092
+ `statistics.quantiles`' default ("exclusive") method.
1093
+ """
1094
+ return ["Array"] + quantiles(_arr_vals(s), n=4)
1095
+
1096
+ def InterquartileRange(s):
1097
+ """
1098
+ ["InterquartileRange", array]
1099
+ Q3 - Q1.
1100
+ """
1101
+ q1, _, q3 = quantiles(_arr_vals(s), n=4)
1102
+ return q3 - q1
1103
+
1104
+ def Covariance(s):
1105
+ """
1106
+ ["Covariance", array1, array2]
1107
+ Sample covariance of two equal-length collections.
1108
+ """
1109
+ return covariance(_arr_vals_of(s[1]), _arr_vals_of(s[2]))
1110
+
1111
+ def Correlation(s):
1112
+ """
1113
+ ["Correlation", array1, array2]
1114
+ The Pearson correlation coefficient of two equal-length
1115
+ collections.
1116
+ """
1117
+ return correlation(_arr_vals_of(s[1]), _arr_vals_of(s[2]))
1118
+
566
1119
  def Any(s):
567
1120
  evaluated = f(s[1], c)
568
1121
  if isinstance(evaluated, list) and evaluated[0] == "Array":
@@ -668,6 +1221,29 @@ def create_mathjson_solver(solver_parameters, legacy_v1=False):
668
1221
 
669
1222
  return f(s[-1], c)
670
1223
 
1224
+ def Which(s):
1225
+ """
1226
+ ["Which", cond1, expr1, cond2, expr2, ..., condN, exprN]
1227
+ CortexJS multi-branch conditional: evaluates each `cond` in
1228
+ order and returns the `expr` paired with the first truthy
1229
+ one. Unlike 'Switch' (Python's value-equality dispatch),
1230
+ each `cond` here is itself a boolean expression, not a
1231
+ value to compare against - and unlike `If`'s pair form,
1232
+ the pairs are flat (cond, expr as separate arguments, not
1233
+ nested as [cond, expr]). Returns None (CortexJS `Nothing`)
1234
+ if no condition matches.
1235
+ """
1236
+ args = s[1:]
1237
+ if len(args) % 2 != 0:
1238
+ raise ValueError(
1239
+ "'Which' requires an even number of parameters "
1240
+ "(condition, value, ...)"
1241
+ )
1242
+ for i in range(0, len(args), 2):
1243
+ if f(args[i], c):
1244
+ return f(args[i + 1], c)
1245
+ return None
1246
+
671
1247
  def In(s):
672
1248
  if len(s) != 3:
673
1249
  raise ValueError("Wrong parameters for 'In'")
@@ -722,6 +1298,316 @@ def create_mathjson_solver(solver_parameters, legacy_v1=False):
722
1298
  raise ValueError("Wrong parameters for 'Str'")
723
1299
  return f"{f(s[1])}"
724
1300
 
1301
+ def String(s):
1302
+ """
1303
+ ["String", value1, value2, ...]
1304
+ Concatenates the default string representation of each
1305
+ argument. Distinct from `Str` (single argument) and from
1306
+ `StringJoin` (joins the elements of a single array).
1307
+ """
1308
+ return "".join(str(f(x, c)) for x in s[1:])
1309
+
1310
+ def StringJoin(s):
1311
+ """
1312
+ ["StringJoin", array] or ["StringJoin", array, separator]
1313
+ Joins the (stringified) elements of `array` with
1314
+ `separator` (default ""). Distinct from `Join`, which
1315
+ concatenates multiple arrays together.
1316
+ """
1317
+ values = [str(v) for v in _arr_vals(s)]
1318
+ separator = f(s[2], c) if len(s) > 2 else ""
1319
+ return separator.join(values)
1320
+
1321
+ def Utf8(s):
1322
+ """
1323
+ ["Utf8", string]
1324
+ List of UTF-8 byte values representing `string`.
1325
+ """
1326
+ return ["Array"] + list(f(s[1], c).encode("utf-8"))
1327
+
1328
+ def Utf16(s):
1329
+ """
1330
+ ["Utf16", string]
1331
+ List of UTF-16 code units representing `string` (one
1332
+ array element per 16-bit code unit, matching how
1333
+ JavaScript/CortexJS model a string).
1334
+ """
1335
+ encoded = f(s[1], c).encode("utf-16-le")
1336
+ return ["Array"] + [
1337
+ encoded[i] | (encoded[i + 1] << 8)
1338
+ for i in range(0, len(encoded), 2)
1339
+ ]
1340
+
1341
+ def UnicodeScalars(s):
1342
+ """
1343
+ ["UnicodeScalars", string]
1344
+ List of Unicode scalar (code point) values in `string`.
1345
+ """
1346
+ return ["Array"] + [ord(ch) for ch in f(s[1], c)]
1347
+
1348
+ def StringFrom(s):
1349
+ """
1350
+ ["StringFrom", array, encoding]
1351
+ Converts `array` (a list of code units, as produced by
1352
+ `Utf8`/`Utf16`/`UnicodeScalars`) back into a string.
1353
+ `encoding` is one of "utf-8", "utf-16", "unicode-scalars".
1354
+ """
1355
+ values = _arr_vals(s)
1356
+ encoding = f(s[2], c)
1357
+ if encoding == "utf-8":
1358
+ return bytes(int(v) for v in values).decode("utf-8")
1359
+ elif encoding == "utf-16":
1360
+ raw = b"".join(int(v).to_bytes(2, "little") for v in values)
1361
+ return raw.decode("utf-16-le")
1362
+ elif encoding == "unicode-scalars":
1363
+ return "".join(chr(int(v)) for v in values)
1364
+ else:
1365
+ raise ValueError(f"Unknown encoding: {encoding!r}")
1366
+
1367
+ def Characters(s):
1368
+ """
1369
+ ["Characters", string]
1370
+ Splits `string` into a list of its characters. Approximated
1371
+ at the Unicode code-point level (Python `str` iteration)
1372
+ rather than true extended grapheme clusters (Unicode
1373
+ Annex #29), which would need a dependency this solver
1374
+ doesn't otherwise require - a multi-codepoint grapheme
1375
+ (e.g. an emoji with a modifier) is split into its
1376
+ constituent code points rather than kept whole.
1377
+ """
1378
+ return ["Array"] + list(f(s[1], c))
1379
+
1380
+ def StringSplit(s):
1381
+ """
1382
+ ["StringSplit", string] or ["StringSplit", string, separator]
1383
+ Splits on whitespace if no `separator` is given, else on
1384
+ the literal `separator` string.
1385
+ """
1386
+ string = f(s[1], c)
1387
+ if len(s) > 2:
1388
+ return ["Array"] + string.split(f(s[2], c))
1389
+ return ["Array"] + string.split()
1390
+
1391
+ def StringReplace(s):
1392
+ """
1393
+ ["StringReplace", string, target, replacement]
1394
+ Replaces every occurrence of the literal substring
1395
+ `target` with `replacement` (not pattern-based - see
1396
+ `IsMatch`/`StringMatch` for pattern matching).
1397
+ """
1398
+ return f(s[1], c).replace(f(s[2], c), f(s[3], c))
1399
+
1400
+ def StringCompare(s):
1401
+ """
1402
+ ["StringCompare", string1, string2]
1403
+ -1, 0, or 1 depending on whether `string1` sorts before,
1404
+ equal to, or after `string2` by code-point sequence.
1405
+ """
1406
+ a, b = f(s[1], c), f(s[2], c)
1407
+ return (a > b) - (a < b)
1408
+
1409
+ def IntegerString(s):
1410
+ """
1411
+ ["IntegerString", integer] or ["IntegerString", integer, base]
1412
+ String representation of `integer` in `base` (default 10,
1413
+ 2-36).
1414
+ """
1415
+ value = int(f(s[1], c))
1416
+ base = int(f(s[2], c)) if len(s) > 2 else 10
1417
+ if base == 10:
1418
+ return str(value)
1419
+ if not (2 <= base <= 36):
1420
+ raise ValueError(
1421
+ "'IntegerString' base must be between 2 and 36."
1422
+ )
1423
+ digits = "0123456789abcdefghijklmnopqrstuvwxyz"
1424
+ negative = value < 0
1425
+ value = abs(value)
1426
+ if value == 0:
1427
+ digits_out = "0"
1428
+ else:
1429
+ digits_out = ""
1430
+ while value:
1431
+ value, rem = divmod(value, base)
1432
+ digits_out = digits[rem] + digits_out
1433
+ return ("-" if negative else "") + digits_out
1434
+
1435
+ def DigitsFrom(s):
1436
+ """
1437
+ ["DigitsFrom", string] or ["DigitsFrom", string, base]
1438
+ Parses `string` as an integer in `base` (default 10).
1439
+ """
1440
+ string = f(s[1], c)
1441
+ base = int(f(s[2], c)) if len(s) > 2 else 10
1442
+ return int(string, base)
1443
+
1444
+ def NumberFrom(s):
1445
+ """
1446
+ ["NumberFrom", string]
1447
+ Parses `string` as a number - integer, decimal, or
1448
+ scientific notation.
1449
+ """
1450
+ string = f(s[1], c).strip()
1451
+ try:
1452
+ return int(string)
1453
+ except ValueError:
1454
+ return float(string)
1455
+
1456
+ def StringRepeat(s):
1457
+ """
1458
+ ["StringRepeat", string, n]
1459
+ Concatenates `n` copies of `string`. Capped at
1460
+ `_MAX_STRING_REPEAT_LENGTH` characters, since `n` is a
1461
+ user-controlled value that would otherwise make this an
1462
+ unbounded memory-exhaustion primitive.
1463
+ """
1464
+ string = f(s[1], c)
1465
+ n = int(f(s[2], c))
1466
+ if n < 0:
1467
+ raise ValueError("'StringRepeat' count must be non-negative.")
1468
+ if len(string) * n > _MAX_STRING_REPEAT_LENGTH:
1469
+ raise ValueError(
1470
+ f"'StringRepeat' result would exceed the "
1471
+ f"{_MAX_STRING_REPEAT_LENGTH}-character limit."
1472
+ )
1473
+ return string * n
1474
+
1475
+ def _pad(string, length, pad, prepend):
1476
+ if length > _MAX_STRING_REPEAT_LENGTH:
1477
+ raise ValueError(
1478
+ f"Pad length must not exceed "
1479
+ f"{_MAX_STRING_REPEAT_LENGTH} characters."
1480
+ )
1481
+ if len(string) >= length or not pad:
1482
+ return string
1483
+ needed = length - len(string)
1484
+ full_pad = (pad * (needed // len(pad) + 1))[:needed]
1485
+ return full_pad + string if prepend else string + full_pad
1486
+
1487
+ def PadStart(s):
1488
+ """
1489
+ ["PadStart", string, length] or
1490
+ ["PadStart", string, length, pad]
1491
+ Pads `string` on the left to `length` characters using
1492
+ `pad` (default a single space), truncating `pad` as
1493
+ needed to fit exactly.
1494
+ """
1495
+ pad = f(s[3], c) if len(s) > 3 else " "
1496
+ return _pad(f(s[1], c), int(f(s[2], c)), pad, prepend=True)
1497
+
1498
+ def PadEnd(s):
1499
+ """
1500
+ ["PadEnd", string, length] or ["PadEnd", string, length, pad]
1501
+ Pads `string` on the right to `length` characters using
1502
+ `pad` (default a single space), truncating `pad` as
1503
+ needed to fit exactly.
1504
+ """
1505
+ pad = f(s[3], c) if len(s) > 3 else " "
1506
+ return _pad(f(s[1], c), int(f(s[2], c)), pad, prepend=False)
1507
+
1508
+ _VALID_REGEX_FLAGS = set("ims")
1509
+
1510
+ def _require_re2():
1511
+ if not RE2_AVAILABLE:
1512
+ raise ImportError(
1513
+ "RegExp/IsMatch/StringMatch/StringMatchAll require "
1514
+ "'google-re2'. Install with "
1515
+ "'pip install mathjson-solver[regex]' "
1516
+ "(or 'pip install google-re2')."
1517
+ )
1518
+
1519
+ def _compile_regex(pattern_str, flags_str=""):
1520
+ if not set(flags_str) <= _VALID_REGEX_FLAGS:
1521
+ raise ValueError(
1522
+ f"Unsupported regex flag(s) in {flags_str!r}; only "
1523
+ f"'i', 'm', 's' are supported."
1524
+ )
1525
+ prefixed = f"(?{flags_str})" + pattern_str if flags_str else pattern_str
1526
+ try:
1527
+ return re2.compile(prefixed)
1528
+ except re2.error as e:
1529
+ raise ValueError(f"Invalid pattern {pattern_str!r}: {e}") from e
1530
+
1531
+ def _resolve_pattern(expr):
1532
+ """
1533
+ Evaluates `expr` and returns a compiled RE2 pattern -
1534
+ unchanged if it's already one (e.g. produced by a nested
1535
+ `RegExp` call), else compiled fresh (no flags) if it's a
1536
+ plain string.
1537
+
1538
+ Uses RE2 rather than Python's `re`: RE2 guarantees
1539
+ linear-time matching (no catastrophic backtracking is
1540
+ possible, by construction of the engine), at the cost of
1541
+ not supporting backreferences or lookaround - a
1542
+ deliberate trade-off for a solver that evaluates
1543
+ untrusted expressions with no execution budget of its own.
1544
+ """
1545
+ _require_re2()
1546
+ value = f(expr, c)
1547
+ if isinstance(value, _RE2_PATTERN_TYPE):
1548
+ return value
1549
+ if isinstance(value, str):
1550
+ return _compile_regex(value)
1551
+ raise ValueError(
1552
+ "Expected a pattern string or a RegExp value."
1553
+ )
1554
+
1555
+ def RegExp(s):
1556
+ """
1557
+ ["RegExp", pattern] or ["RegExp", pattern, flags]
1558
+ Compiles `pattern` (RE2 syntax - see `_resolve_pattern`)
1559
+ into a reusable pattern value, for passing to
1560
+ `IsMatch`/`StringMatch`/`StringMatchAll`. `flags` is a
1561
+ string made up of "i" (case-insensitive), "m" (multiline
1562
+ anchors), "s" (dot matches newline).
1563
+ """
1564
+ _require_re2()
1565
+ pattern_str = f(s[1], c)
1566
+ flags_str = f(s[2], c) if len(s) > 2 else ""
1567
+ return _compile_regex(pattern_str, flags_str)
1568
+
1569
+ def IsMatch(s):
1570
+ """
1571
+ ["IsMatch", string, pattern]
1572
+ Whether `string` contains a match for `pattern` (a plain
1573
+ pattern string, or a `RegExp` value) anywhere within it.
1574
+ """
1575
+ pattern = _resolve_pattern(s[2])
1576
+ return pattern.search(f(s[1], c)) is not None
1577
+
1578
+ def _match_record(m):
1579
+ return [
1580
+ "Array",
1581
+ m.group(0),
1582
+ m.start() + 1, # 1-indexed, matching this solver's
1583
+ m.end(), # other CortexJS-compat index
1584
+ # conventions (At, Range, ...)
1585
+ ["Array"] + list(m.groups()),
1586
+ ]
1587
+
1588
+ def StringMatch(s):
1589
+ """
1590
+ ["StringMatch", string, pattern]
1591
+ The first match of `pattern` in `string`, as
1592
+ ["Array", matched_text, start, end, ["Array", group1, ...]]
1593
+ (1-indexed `start`, exclusive `end`), or None if there's
1594
+ no match.
1595
+ """
1596
+ pattern = _resolve_pattern(s[2])
1597
+ m = pattern.search(f(s[1], c))
1598
+ return _match_record(m) if m else None
1599
+
1600
+ def StringMatchAll(s):
1601
+ """
1602
+ ["StringMatchAll", string, pattern]
1603
+ All non-overlapping matches of `pattern` in `string`,
1604
+ each in the same shape as `StringMatch`.
1605
+ """
1606
+ pattern = _resolve_pattern(s[2])
1607
+ return ["Array"] + [
1608
+ _match_record(m) for m in pattern.finditer(f(s[1], c))
1609
+ ]
1610
+
725
1611
  def Not(s):
726
1612
  return not f(s[1])
727
1613
 
@@ -912,6 +1798,69 @@ def create_mathjson_solver(solver_parameters, legacy_v1=False):
912
1798
  except TypeError:
913
1799
  return False
914
1800
 
1801
+ def IdenticallyEqual(s):
1802
+ """
1803
+ ["IdenticallyEqual", a, b]
1804
+ Stricter than `StrictEqual`: true only if `a` and `b` have
1805
+ the same Python type *and* are equal - e.g. `1` and `1.0`
1806
+ are `StrictEqual` but not `IdenticallyEqual`.
1807
+ """
1808
+ a = f(s[1], c)
1809
+ b = f(s[2], c)
1810
+ return type(a) == type(b) and a == b
1811
+
1812
+ def Congruent(s):
1813
+ """
1814
+ ["Congruent", a, b, modulus]
1815
+ Whether `a` and `b` are congruent modulo `modulus`, i.e.
1816
+ `(a - b) % modulus == 0`.
1817
+ """
1818
+ a = f(s[1], c)
1819
+ b = f(s[2], c)
1820
+ modulus = f(s[3], c)
1821
+ return (a - b) % modulus == 0
1822
+
1823
+ def _rational_parts(s):
1824
+ """
1825
+ Numerator/denominator pair for `s[1]`. If `s[1]` is itself
1826
+ an unevaluated `["Rational", n, d]` expression, its
1827
+ declared `n`/`d` are used exactly. Otherwise, the
1828
+ evaluated value is reconstructed as the closest fraction
1829
+ with a bounded denominator - a best-effort approximation,
1830
+ not exact/symbolic, since this solver has no dedicated
1831
+ rational-number type carried through arithmetic (see
1832
+ `Rational`'s docstring).
1833
+ """
1834
+ expr = s[1]
1835
+ if (
1836
+ isinstance(expr, list)
1837
+ and len(expr) == 3
1838
+ and expr[0] == "Rational"
1839
+ ):
1840
+ return int(f(expr[1], c)), int(f(expr[2], c))
1841
+ value = f(expr, c)
1842
+ if isinstance(value, int):
1843
+ return value, 1
1844
+ frac = Fraction(value).limit_denominator(10**6)
1845
+ return frac.numerator, frac.denominator
1846
+
1847
+ def Numerator(s):
1848
+ return _rational_parts(s)[0]
1849
+
1850
+ def Denominator(s):
1851
+ return _rational_parts(s)[1]
1852
+
1853
+ def Rational(s):
1854
+ """
1855
+ ["Rational", numerator, denominator]
1856
+ Evaluates to `numerator / denominator` as a plain float -
1857
+ there's no exact rational-number type carried through
1858
+ arithmetic in this solver, so precision beyond a float is
1859
+ only preserved when `Numerator`/`Denominator` read this
1860
+ expression directly, rather than its evaluated value.
1861
+ """
1862
+ return f(s[1], c) / f(s[2], c)
1863
+
915
1864
  def BooleanAnd(s):
916
1865
  """
917
1866
  Boolean AND operation.
@@ -1346,6 +2295,8 @@ def create_mathjson_solver(solver_parameters, legacy_v1=False):
1346
2295
  "IsTrue": lambda s: bool(f(s[1], c)),
1347
2296
  "IsFalse": lambda s: not bool(f(s[1], c)),
1348
2297
  "StrictEqual": lambda s: f(s[1], c) == f(s[2], c),
2298
+ "IdenticallyEqual": IdenticallyEqual,
2299
+ "Congruent": Congruent,
1349
2300
  # "Greater": lambda s: f(s[1], c) > f(s[2], c),
1350
2301
  "Greater": Greater,
1351
2302
  # "GreaterEqual": lambda s: f(s[1], c) >= f(s[2], c),
@@ -1378,6 +2329,8 @@ def create_mathjson_solver(solver_parameters, legacy_v1=False):
1378
2329
  "List": lambda s: ["Array"] + [f(x, c) for x in s[1:]], # CortexJS name for Array
1379
2330
  "In": In,
1380
2331
  "Not_in": Not_in,
2332
+ "Element": In, # CortexJS name for In (["Element", value, set])
2333
+ "NotElement": Not_in, # CortexJS name for Not_in
1381
2334
  "Contains_any_of": Contains_any_of,
1382
2335
  "Contains_all_of": Contains_all_of,
1383
2336
  "Contains_none_of": Contains_none_of,
@@ -1390,6 +2343,34 @@ def create_mathjson_solver(solver_parameters, legacy_v1=False):
1390
2343
  "Floor": Floor,
1391
2344
  "Ceil": Ceil,
1392
2345
  "Str": Str,
2346
+ # --- Strings ---
2347
+ "String": String,
2348
+ "StringJoin": StringJoin,
2349
+ "ToUpperCase": lambda s: f(s[1], c).upper(),
2350
+ "ToLowerCase": lambda s: f(s[1], c).lower(),
2351
+ "CaseFold": lambda s: f(s[1], c).casefold(),
2352
+ "Trim": lambda s: f(s[1], c).strip(),
2353
+ "TrimStart": lambda s: f(s[1], c).lstrip(),
2354
+ "TrimEnd": lambda s: f(s[1], c).rstrip(),
2355
+ "StringSplit": StringSplit,
2356
+ "StringReplace": StringReplace,
2357
+ "StringCompare": StringCompare,
2358
+ "StringRepeat": StringRepeat,
2359
+ "PadStart": PadStart,
2360
+ "PadEnd": PadEnd,
2361
+ "Characters": Characters,
2362
+ "GraphemeClusters": Characters, # CortexJS synonym for Characters
2363
+ "Utf8": Utf8,
2364
+ "Utf16": Utf16,
2365
+ "UnicodeScalars": UnicodeScalars,
2366
+ "StringFrom": StringFrom,
2367
+ "IntegerString": IntegerString,
2368
+ "DigitsFrom": DigitsFrom,
2369
+ "NumberFrom": NumberFrom,
2370
+ "RegExp": RegExp,
2371
+ "IsMatch": IsMatch,
2372
+ "StringMatch": StringMatch,
2373
+ "StringMatchAll": StringMatchAll,
1393
2374
  "Not": Not,
1394
2375
  # "IsDefined": lambda s: s[1] in c,
1395
2376
  "IsDefined": IsDefined,
@@ -1433,7 +2414,7 @@ def create_mathjson_solver(solver_parameters, legacy_v1=False):
1433
2414
  "Arctan": Arctan,
1434
2415
  "Arctan2": lambda s: math.atan2(f(s[1], c), f(s[2], c)),
1435
2416
  "Pi": Pi,
1436
- "Which": Switch, # CortexJS name for Switch
2417
+ "Which": Which, # CortexJS multi-branch conditional (not Switch - see Which's docstring)
1437
2418
  # --- Trigonometric: reciprocal, hyperbolic, area-hyperbolic ---
1438
2419
  "Cot": lambda s: 1 / math.tan(f(s[1], c)),
1439
2420
  "Sec": lambda s: 1 / math.cos(f(s[1], c)),
@@ -1461,6 +2442,12 @@ def create_mathjson_solver(solver_parameters, legacy_v1=False):
1461
2442
  "Degrees": lambda s: math.pi / 180,
1462
2443
  "ExponentialE": lambda s: math.e,
1463
2444
  "GoldenRatio": lambda s: (1 + math.sqrt(5)) / 2,
2445
+ "MachineEpsilon": lambda s: sys.float_info.epsilon,
2446
+ "CatalanConstant": lambda s: 0.915965594177219015054603514932384110774,
2447
+ "EulerGamma": lambda s: 0.5772156649015328606065120900824024310421,
2448
+ "Rational": Rational,
2449
+ "Numerator": Numerator,
2450
+ "Denominator": Denominator,
1464
2451
  # --- Number theory / special functions ---
1465
2452
  "Chop": lambda s: 0 if abs(f(s[1], c)) < 1e-10 else f(s[1], c),
1466
2453
  "Mod": lambda s: f(s[1], c) % f(s[2], c),
@@ -1481,8 +2468,17 @@ def create_mathjson_solver(solver_parameters, legacy_v1=False):
1481
2468
  # --- Statistics ---
1482
2469
  "Variance": Variance,
1483
2470
  "StandardDeviation": StandardDeviation,
2471
+ "PopulationVariance": PopulationVariance,
2472
+ "PopulationStandardDeviation": PopulationStandardDeviation,
2473
+ "Mode": Mode,
2474
+ "Quartiles": Quartiles,
2475
+ "InterquartileRange": InterquartileRange,
2476
+ "Covariance": Covariance,
2477
+ "Correlation": Correlation,
1484
2478
  # --- Collections ---
1485
2479
  "First": First,
2480
+ "Second": Second,
2481
+ "Third": Third,
1486
2482
  "Last": Last,
1487
2483
  "Rest": Rest,
1488
2484
  "Most": Most,
@@ -1494,6 +2490,42 @@ def create_mathjson_solver(solver_parameters, legacy_v1=False):
1494
2490
  "Unique": Unique,
1495
2491
  "Zip": Zip,
1496
2492
  "At": At,
2493
+ "Take": Take,
2494
+ "Drop": Drop,
2495
+ "TakeWhile": TakeWhile,
2496
+ "DropWhile": DropWhile,
2497
+ "Contains": Contains,
2498
+ "IndexOf": IndexOf,
2499
+ "IndexWhere": IndexWhere,
2500
+ "Find": Find,
2501
+ "CountIf": CountIf,
2502
+ "Position": Position,
2503
+ "RotateLeft": RotateLeft,
2504
+ "RotateRight": RotateRight,
2505
+ "MaxBy": MaxBy,
2506
+ "MinBy": MinBy,
2507
+ "ArgMax": ArgMax,
2508
+ "ArgMin": ArgMin,
2509
+ "Ordering": Ordering,
2510
+ "FlatMap": FlatMap,
2511
+ "Scan": Scan,
2512
+ "Differences": Differences,
2513
+ "Fold": Fold,
2514
+ "Dedup": Dedup,
2515
+ "Append": Appended, # CortexJS name for Appended
2516
+ "Insert": Insert,
2517
+ "DeleteAt": DeleteAt,
2518
+ "ReplaceAt": ReplaceAt,
2519
+ "Partition": Partition,
2520
+ "Chunk": Chunk,
2521
+ "GroupBy": GroupBy,
2522
+ "ChunkBy": ChunkBy,
2523
+ "Tally": Tally,
2524
+ # --- Set algebra (over Array - no dedicated Set type) ---
2525
+ "Union": Union,
2526
+ "Intersection": Intersection,
2527
+ "SetMinus": SetMinus,
2528
+ "SymmetricDifference": SymmetricDifference,
1497
2529
  }
1498
2530
  if not s:
1499
2531
  # Empty equation given - []
@@ -1591,15 +2623,46 @@ def extract_variables(s: Union[list, int, float, str], li: set, ignore_list: set
1591
2623
  "ContainsAnyOf",
1592
2624
  "ContainsAllOf",
1593
2625
  "ContainsNoneOf",
2626
+ "Element",
2627
+ "NotElement",
1594
2628
  "Int",
1595
2629
  "Float",
1596
2630
  "Floor",
1597
2631
  "Ceil",
1598
2632
  "Str",
2633
+ "String",
2634
+ "StringJoin",
2635
+ "ToUpperCase",
2636
+ "ToLowerCase",
2637
+ "CaseFold",
2638
+ "Trim",
2639
+ "TrimStart",
2640
+ "TrimEnd",
2641
+ "StringSplit",
2642
+ "StringReplace",
2643
+ "StringCompare",
2644
+ "StringRepeat",
2645
+ "PadStart",
2646
+ "PadEnd",
2647
+ "Characters",
2648
+ "GraphemeClusters",
2649
+ "Utf8",
2650
+ "Utf16",
2651
+ "UnicodeScalars",
2652
+ "StringFrom",
2653
+ "IntegerString",
2654
+ "DigitsFrom",
2655
+ "NumberFrom",
2656
+ "RegExp",
2657
+ "IsMatch",
2658
+ "StringMatch",
2659
+ "StringMatchAll",
1599
2660
  "Not",
1600
2661
  "IsDefined",
1601
2662
  "IsUndefined",
1602
2663
  "StrictEqual",
2664
+ "IdenticallyEqual",
2665
+ "Congruent",
1603
2666
  "NotEqual",
1604
2667
  "StrictSwitch",
1605
2668
  "Map",
@@ -1672,6 +2735,12 @@ def extract_variables(s: Union[list, int, float, str], li: set, ignore_list: set
1672
2735
  "Degrees",
1673
2736
  "ExponentialE",
1674
2737
  "GoldenRatio",
2738
+ "MachineEpsilon",
2739
+ "CatalanConstant",
2740
+ "EulerGamma",
2741
+ "Rational",
2742
+ "Numerator",
2743
+ "Denominator",
1675
2744
  "Chop",
1676
2745
  "Mod",
1677
2746
  "Clamp",
@@ -1689,7 +2758,16 @@ def extract_variables(s: Union[list, int, float, str], li: set, ignore_list: set
1689
2758
  "Equivalent",
1690
2759
  "Variance",
1691
2760
  "StandardDeviation",
2761
+ "PopulationVariance",
2762
+ "PopulationStandardDeviation",
2763
+ "Mode",
2764
+ "Quartiles",
2765
+ "InterquartileRange",
2766
+ "Covariance",
2767
+ "Correlation",
1692
2768
  "First",
2769
+ "Second",
2770
+ "Third",
1693
2771
  "Last",
1694
2772
  "Rest",
1695
2773
  "Most",
@@ -1701,11 +2779,48 @@ def extract_variables(s: Union[list, int, float, str], li: set, ignore_list: set
1701
2779
  "Unique",
1702
2780
  "Zip",
1703
2781
  "At",
2782
+ "Take",
2783
+ "Drop",
2784
+ "TakeWhile",
2785
+ "DropWhile",
2786
+ "Contains",
2787
+ "IndexOf",
2788
+ "IndexWhere",
2789
+ "Find",
2790
+ "CountIf",
2791
+ "Position",
2792
+ "RotateLeft",
2793
+ "RotateRight",
2794
+ "MaxBy",
2795
+ "MinBy",
2796
+ "ArgMax",
2797
+ "ArgMin",
2798
+ "Ordering",
2799
+ "FlatMap",
2800
+ "Scan",
2801
+ "Differences",
2802
+ "Fold",
2803
+ "Dedup",
2804
+ "Append",
2805
+ "Insert",
2806
+ "DeleteAt",
2807
+ "ReplaceAt",
2808
+ "Partition",
2809
+ "Chunk",
2810
+ "GroupBy",
2811
+ "ChunkBy",
2812
+ "Tally",
2813
+ "Union",
2814
+ "Intersection",
2815
+ "SetMinus",
2816
+ "SymmetricDifference",
1704
2817
  ]
1705
2818
  if isinstance(s, str):
1706
2819
  if s in ignore_list:
1707
2820
  return li
1708
- if s not in constructs:
2821
+ # "True"/"False" are boolean literals (see `f`'s handling of them),
2822
+ # not solver-parameter references, so they're never free variables.
2823
+ if s not in constructs and s not in ("True", "False"):
1709
2824
  li.add(s)
1710
2825
  return li
1711
2826
  elif isinstance(s, list):
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: mathjson-solver
3
- Version: 2.2.0
3
+ Version: 2.2.1
4
4
  Summary: Utilities for MathJSON evaluation
5
5
  Project-URL: Homepage, https://github.com/LongenesisLtd/mathjson-solver
6
6
  Project-URL: Bug Tracker, https://github.com/LongenesisLtd/mathjson-solver/issues
@@ -9,7 +9,11 @@ License-Expression: MIT
9
9
  License-File: LICENSE
10
10
  Classifier: Operating System :: OS Independent
11
11
  Classifier: Programming Language :: Python :: 3
12
- Requires-Python: >=3.6
12
+ Requires-Python: >=3.10
13
+ Provides-Extra: integration
14
+ Requires-Dist: numpy; extra == 'integration'
15
+ Provides-Extra: regex
16
+ Requires-Dist: google-re2; extra == 'regex'
13
17
  Description-Content-Type: text/markdown
14
18
 
15
19
  # MathJSON Solver
@@ -42,9 +46,11 @@ A reliable Python library for numerically evaluating mathematical expressions in
42
46
  pip install mathjson-solver
43
47
  ```
44
48
 
45
- **Requirements:** Python 3.7+
49
+ **Requirements:** Python 3.10+
46
50
 
47
- **Optional:** numpy (only required for `TrapezoidalIntegrate` function)
51
+ **Optional:**
52
+ - `pip install mathjson-solver[integration]` (installs numpy; only required for `TrapezoidalIntegrate`)
53
+ - `pip install mathjson-solver[regex]` (installs [google-re2](https://pypi.org/project/google-re2/); only required for `RegExp`/`IsMatch`/`StringMatch`/`StringMatchAll`)
48
54
 
49
55
  ## Quick Start
50
56
 
@@ -112,16 +118,18 @@ The library supports a comprehensive set of mathematical operations:
112
118
  * **Arithmetic:** Add, Sum, Subtract, Multiply, Divide, Negate, Power, Square, Root, Sqrt, Abs, Round, Floor, Ceil
113
119
  * **Trigonometry:** Sin, Cos, Tan, Arcsin, Arccos, Arctan, Arctan2, Cot, Sec, Csc (+ inverses), Sinh, Cosh, Tanh, Coth, Sech, Csch (+ inverses), Hypot, Sinc
114
120
  * **Logarithms:** Log (base 10, or base b), Log2/Lb, Log10/Lg, Ln (natural log), LogOnePlus, Exp
115
- * **Comparison:** Equal, StrictEqual, NotEqual, Greater, GreaterEqual, Less, LessEqual
116
- * **Logic & Sets:** Any, All, Not, And, Or, Xor, Nand, Nor, Implies, Equivalent, In, NotIn, ContainsAnyOf, ContainsAllOf, ContainsNoneOf
117
- * **Statistics:** Average/Mean, Max, Min (both list and variadic forms), Median, Variance, StandardDeviation, Length/Count
121
+ * **Comparison:** Equal, StrictEqual, IdenticallyEqual, NotEqual, Greater, GreaterEqual, Less, LessEqual, Congruent
122
+ * **Logic & Sets:** Any, All, Not, And, Or, Xor, Nand, Nor, Implies, Equivalent, In/Element, NotIn/NotElement, ContainsAnyOf, ContainsAllOf, ContainsNoneOf, bare `True`/`False` literals, Union, Intersection, SetMinus, SymmetricDifference (over arrays - no dedicated Set type)
123
+ * **Statistics:** Average/Mean, Max, Min (both list and variadic forms), Median, Mode, Variance, StandardDeviation, PopulationVariance, PopulationStandardDeviation, Quartiles, InterquartileRange, Covariance, Correlation, Length/Count
118
124
  * **Functional Programming:** Map/StrictMap, Reduce, Filter, Product (all also accept CortexJS calling conventions, including `Function` lambdas)
119
- * **Arrays:** Array/List creation, GenerateRange, Range, AtIndex, At, Slice, Appended, First, Last, Rest, Most, Reverse, Sort, Unique, Join, Zip, IsEmpty, CumulativeSum, CumulativeProduct
120
- * **Control Flow:** If statements (Python pair form and CortexJS flat form), Switch-Case/Which, Constants definition
125
+ * **Arrays:** Array/List creation, GenerateRange, Range, AtIndex, At, Slice, Appended/Append, First, Second, Third, Last, Rest, Most, Reverse, Sort, Unique, Dedup, Join, Zip, IsEmpty, CumulativeSum, CumulativeProduct, Take, Drop, TakeWhile, DropWhile, Contains, IndexOf, IndexWhere, Find, CountIf, Position, RotateLeft, RotateRight, MaxBy, MinBy, ArgMax, ArgMin, Ordering, FlatMap, Scan, Differences, Fold, Insert, DeleteAt, ReplaceAt, Partition, Chunk, GroupBy, ChunkBy, Tally
126
+ * **Control Flow:** If statements (Python pair form and CortexJS flat form), Switch/StrictSwitch (value-equality case dispatch), Which (CortexJS flat condition/value chain), Constants definition
121
127
  * **Type Conversion:** Int, Float, Str, IsDefined
128
+ * **Strings:** String, StringJoin, ToUpperCase, ToLowerCase, CaseFold, Trim, TrimStart, TrimEnd, StringSplit, StringReplace, StringCompare, StringRepeat, PadStart, PadEnd, Characters/GraphemeClusters, Utf8, Utf16, UnicodeScalars, StringFrom, IntegerString, DigitsFrom, NumberFrom
129
+ * **Pattern Matching (requires the optional `regex` extra, `pip install mathjson-solver[regex]`):** RegExp, IsMatch, StringMatch, StringMatchAll — backed by [RE2](https://github.com/google/re2) rather than Python's `re`, for a hard guarantee against catastrophic backtracking (no backreferences/lookaround, as a deliberate trade-off for that guarantee)
122
130
  * **Date/Time:** Strptime, Strftime, Today, Now, TimeDelta functions (Weeks, Days, Hours, Minutes)
123
- * **Number Theory:** Chop, Mod, Clamp, GCD, LCM, Factorial, Binomial, IsPrime, Erf, Erfc
124
- * **Integration:** TrapezoidalIntegrate (requires numpy), Interp, FindIntervalIndex, Variable references
131
+ * **Number Theory:** Chop, Mod, Clamp, GCD, LCM, Factorial, Binomial, IsPrime, Erf, Erfc, Rational, Numerator, Denominator, MachineEpsilon, CatalanConstant, EulerGamma
132
+ * **Integration (requires the optional `integration` extra, `pip install mathjson-solver[integration]`):** TrapezoidalIntegrate. Also in this group but with no extra dependency: Interp, FindIntervalIndex, Variable references
125
133
  * **Advanced:** HasMatchingSublist for pattern matching
126
134
  * **Constants:** Pi, Degrees, ExponentialE, GoldenRatio
127
135
 
@@ -0,0 +1,6 @@
1
+ mathjson_solver/__init__.py,sha256=09fRBSoObQ-chsHOTNjWe05QiOljufWSCA-nmYfMJpo,165
2
+ mathjson_solver/__main__.py,sha256=FsMKrom9nkjaOKIwqB0TJBf9JgHBwaUNjEVByHWAktQ,108804
3
+ mathjson_solver-2.2.1.dist-info/METADATA,sha256=NDFKz3L7hNs1Crx9QwVhrfRXzqzEpsKZTN2nXnD3z8g,11659
4
+ mathjson_solver-2.2.1.dist-info/WHEEL,sha256=zOwg4jB6zX2kU910N-cMawjivD6tO8NEWvE12je1bVk,87
5
+ mathjson_solver-2.2.1.dist-info/licenses/LICENSE,sha256=uWXG6XqeqlBciRTAN8ZPXcNrZnzq1V5Dc7QzB2VGCjY,1071
6
+ mathjson_solver-2.2.1.dist-info/RECORD,,
@@ -1,6 +0,0 @@
1
- mathjson_solver/__init__.py,sha256=09fRBSoObQ-chsHOTNjWe05QiOljufWSCA-nmYfMJpo,165
2
- mathjson_solver/__main__.py,sha256=CUcrpYbE8_WM7vvqiSzshx85dkOrVFbfEQFVLhYOgqo,65248
3
- mathjson_solver-2.2.0.dist-info/METADATA,sha256=OzrmaUwKynG6l8QNO1TY09MppzYBfmy19kAc5rkAeic,9821
4
- mathjson_solver-2.2.0.dist-info/WHEEL,sha256=zOwg4jB6zX2kU910N-cMawjivD6tO8NEWvE12je1bVk,87
5
- mathjson_solver-2.2.0.dist-info/licenses/LICENSE,sha256=uWXG6XqeqlBciRTAN8ZPXcNrZnzq1V5Dc7QzB2VGCjY,1071
6
- mathjson_solver-2.2.0.dist-info/RECORD,,