Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #scan the infix string from left to right
- #initialise an empty stack
- #if the scanned character is an operand then add it to the postix string
- #if the scanned character is an operator and the stack is empty, push the character to the stack
- #if the scanned character is operator and stack not empty, compare the precedence of the character with the elemont on top of the stack, if the top of stack has higher precedence over the scanned character then pop the stack else push the scanned character to stock, repeat this step as long as stack is not empty and top stack has precedence over the character.
- #repeat until all characters are scanned.
- #pop contents of the stack 1 by 1 onto the end of the postfix string until the stack is empty
- #return the postfix string
- def inToPost(infix):
- #initialise empty stack and output
- postfix = ""
- stack = []
- #scan each character left to right
- for count in range(0, len(infix)):
- token = infix[count]
- #print token
- #print postfix
- #print stack
- if isNumber(token):
- #if scanned character is an operand then add to postfix string
- postfix += token
- elif isOperator(token):
- #scanned character is an operator
- comparing = True
- while comparing == True:
- if len(stack) == 0:
- #if stack is empty, push token onto the stack
- stack.append(token)
- comparing = False
- elif precedence(token) >= precedence(stack[-1]):
- stack.append(token)
- comparing = False
- else:
- postfix += stack.pop()
- '''
- else:
- #compare precedence
- comparing = True
- while comparing == True:
- if precedence(stack[-1]) <= precedence(token):
- #top of stack has lower precedence, add token to output
- comparing = False
- postfix += token
- else:
- #top of stack has higher precedence, add top of stack to output
- postfix += stack.pop()
- if len(stack) == 0:
- stack.append(token)
- comparing = False
- print postfix
- #end of while
- '''
- #end of isOperator
- else:
- print "invalid token: " + token + "discarded"
- #print "\n"
- #print postfix
- #print stack
- #print "\n###~###\n"
- #pop contents of stack onto postfix string
- for count in range(0, len(stack)):
- postfix += stack.pop()
- return postfix
- def isNumber(token):
- try:
- token = int(token)
- return True
- except:
- return False
- def isOperator(token):
- if token in ["+", "-", "*", "/", "^"]:
- return True
- else:
- return False
- def precedence(token):
- #bidmas
- if token == "-":
- return 1
- elif token == "+":
- return 1
- elif token == "*":
- return 2
- elif token == "/":
- return 2
- elif token == "^":
- return 3
- return 0
- expression = "1+2*3-4"
- #expression = "3+4*5/6"
- print inToPost(expression)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement