forked from sympy/sympy
-
Notifications
You must be signed in to change notification settings - Fork 1
/
mathematica.py
57 lines (39 loc) · 1.52 KB
/
mathematica.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
from __future__ import print_function, division
from re import match
from sympy import sympify
def mathematica(s):
return sympify(parse(s))
def parse(s):
s = s.strip()
#Begin rules
rules = (
(r"\A(\w+)\[([^\]]+[^\[]*)\]\Z", # Function call
lambda m: translateFunction(
m.group(1)) + "(" + parse(m.group(2)) + ")" ),
(r"\((.+)\)\((.+)\)", # Parenthesized implied multiplication
lambda m: "(" + parse(m.group(1)) + ")*(" + parse(m.group(2)) + ")" ),
(r"\A\((.+)\)\Z", # Parenthesized expression
lambda m: "(" + parse(m.group(1)) + ")" ),
(r"\A(.*[\w\.])\((.+)\)\Z", # Implied multiplication - a(b)
lambda m: parse(m.group(1)) + "*(" + parse(m.group(2)) + ")" ),
(r"\A\((.+)\)([\w\.].*)\Z", # Implied multiplication - (a)b
lambda m: "(" + parse(m.group(1)) + ")*" + parse(m.group(2)) ),
(r"\A([\d\.]+)([a-zA-Z].*)\Z", # Implied multiplicatin - 2a
lambda m: parse(m.group(1)) + "*" + parse(m.group(2)) ),
(r"\A([^=]+)([\^\-\*/\+=]=?)(.+)\Z", # Infix operator
lambda m: parse(m.group(1)) + translateOperator(m.group(2)) + parse(m.group(3)) ))
#End rules
for rule, action in rules:
m = match(rule, s)
if m:
return action(m)
return s
def translateFunction(s):
if s.startswith("Arc"):
return "a" + s[3:]
return s.lower()
def translateOperator(s):
dictionary = {'^': '**'}
if s in dictionary:
return dictionary[s]
return s