forked from sympy/sympy
-
Notifications
You must be signed in to change notification settings - Fork 1
/
mathematica.py
50 lines (37 loc) · 1.41 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
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[0:3] == "Arc":
return "a" + s[3:]
return s.lower()
def translateOperator (s):
dictionary = {'^':'**'}
if s in dictionary:
return dictionary[s]
return s