Skip to content

Instantly share code, notes, and snippets.

@seyyah
Forked from anonymous/as10_s4b.py
Created April 12, 2011 14:49
Show Gist options
  • Save seyyah/915628 to your computer and use it in GitHub Desktop.
Save seyyah/915628 to your computer and use it in GitHub Desktop.
from warnings import warn
def buildParseTree(fpexp):
L,R,O,V = 1,2,3,4
state = None
fplist = fpexp.split()
pStack = Stack()
eTree = BinaryTree('')
pStack.push(eTree)
currentTree = eTree
for i in fplist:
if not state and i in ')+-*/': raise Exception(') ve islec olamaz')
if i == '(':
if state == V: raise Exception('islenen+(')
if state == R: raise Exception(')+(')
currentTree.insertLeft('')
pStack.push(currentTree)
currentTree = currentTree.getLeftChild()
state = L
elif i not in '+-*/)':
if state == V: raise Exception('islenen+islenen')
if state == R: raise Exception(') + islenen')
currentTree.setRootVal(eval(i))
parent = pStack.pop()
currentTree = parent
state = V
elif i in '+-*/':
if state == O: raise Exception('islec+islec')
if state == L: raise Exception('(+islec')
currentTree.setRootVal(i)
currentTree.insertRight('')
pStack.push(currentTree)
currentTree = currentTree.getRightChild()
state = O
elif i == ')':
if state == O: raise Exception('islec+)')
if state == L: warn('(+)')
currentTree = pStack.pop()
state = R
return eTree
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment