'How do I convert a symbolic math expression (containing variables) into prefix notation?
I am trying to convert math expressions (which contain trigonometric func, log func, etc and variable x ) into prefix form.
- I have generated the expressions in the form of a pandas dataframe which contains expressions and their derivatives (in 2 separate columns)
- I need to convert them into prefix notation
- After running the code, the values are changing to <pythonds.trees.binaryTree.BinaryTree object at 0x00000137A622CC40>
Below is my code:
import sympy as sp
import pandas as pd
import numpy as np
from pythonds.basic import Stack
from pythonds.trees import BinaryTree
def buildParseTree(fpexp):
fplist = fpexp.split()
pStack = Stack()
eTree = BinaryTree('')
pStack.push(eTree)
currentTree = eTree
for i in fplist:
if i == '(':
currentTree.insertLeft('')
pStack.push(currentTree)
currentTree = currentTree.getLeftChild()
elif i in ['+', '-', '*', '/','sin','cos','tan','cot','sec','csc','log','sqrt']:
currentTree.setRootVal(i)
currentTree.insertRight('')
pStack.push(currentTree)
currentTree = currentTree.getRightChild()
elif i == ')':
currentTree = pStack.pop()
elif i.isnumeric() or i=='x':
try:
currentTree.setRootVal(i)
parent = pStack.pop()
currentTree = parent
except ValueError:
raise ValueError("token '{}' is not a valid integer".format(i))
return eTree
def preorder(self):
print(self.key)
if self.leftChild:
self.leftChild.preorder()
if self.rightChild:
self.rightChild.preorder()
def separator(element):
# element=dataset['Answers'][0]
a=list(element)
temp_list = []
# print(a)
i=0
while(i<len(a)):
if(a[i].isalpha() and (a[i]!="x")):
joinedstring = (''.join(a[i:i+3:]))
temp_list.append(joinedstring)
i+=3
else:
temp_list.append(a[i])
i+=1
return temp_list
ques = []
ans = []
count = 0
x = sp.symbols("x")
i = sp.symbols("i")
for i in range (1,101):
ques.append("sin"+"("+str(i)+"*"+ "x"+")")
ques.append("cos"+"("+str(i)+"*"+ "x"+")")
ques.append("tan"+"("+str(i)+"*"+ "x"+")")
ques.append("cot"+"("+str(i)+"*"+ "x"+")")
ques.append("sec"+"("+str(i)+"*"+ "x"+")")
ques.append("csc"+"("+str(i)+"*"+ "x"+")")
ques.append("sqrt"+"("+str(i)+"*"+ "x"+")")
ques.append("log"+"("+str(i)+"*"+ "x"+")")
count+=8
for q in ques:
k=(sp.diff(q))
ans.append(str(k))
dataset = pd.DataFrame(list(zip(ques,ans)), columns=['Questions','Answers'])
print(dataset)
print(count)
## Exporting Data into Excel file
# # saving the excel
# sol.to_excel(file_name)
## Converting the generated math expressions into lists and separating operators and operands
for ques in dataset['Questions']:
ques = separator(ques)
print(ques)
for ans in dataset['Answers']:
ans = separator(ans)
print(ans)
## Converting the differentiated expressions into prefix notation
for i in range(count):
pt = buildParseTree(str(dataset.loc[i].at['Questions']))
pt.preorder()
dataset.loc[i].at['Questions'] = pt
pt = buildParseTree(str(dataset.loc[i].at['Answers']))
pt.preorder()
dataset.loc[i].at['Answers'] = pt
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
