예제 #1
0
def infix_to_postfix(infixexpr):
    """Converts an infix expression to an equivalent postfix expression """
    prec = {'^':4, '*': 3, '/': 3, '+': 2, '-': 2, '(': 1}
    opstack = StackArray(30)
    postfixList = []
    tokenList = infixexpr.split(' ')#returns an array with elements split
    for tok in tokenList:
        if tok not in "^*()-/+": #if token is a number put in the list
            postfixList.append(tok)
        elif tok == '(': #if token is open parenthesis put it in list output
            opstack.push(tok)
        elif tok == ')': #if token is close parenthesis
            toptoken = opstack.pop() #take the top token of stack
            while toptoken != '(': #pop through the stack and append to output list until you get to the open parenthesis
                postfixList.append(toptoken)
                toptoken = opstack.pop()
        else:
            while (not opstack.is_empty()) and (prec[opstack.peek()] >= prec[tok]):#handle precedence
                if opstack.peek() == '^' and tok == "^":
                    break#dont append
                postfixList.append(opstack.pop())
            opstack.push(tok)

    while not opstack.is_empty():#if empty append everything else
        postfixList.append(opstack.pop())
    return " ".join(postfixList)
예제 #2
0
def infix_to_postfix(infixexpr):
    """Converts an infix expression to an equivalent postfix expression """
    """Signature:  a string containing an infix expression where tokens are space separated is
       the single input parameter and returns a string containing a postfix expression
       where tokens are space separated"""
    operandStack = StackArray(30)
    postfixList = []
    tokenList = infixexpr.split()
    precedence = {"^": 4, "*": 3, "/": 3, "+": 2, "-": 2, "(": 1}
    for token in tokenList:
        if is_valid(token):
            postfixList.append(token)
        else:
            if token == '(':
                operandStack.push(token)
            elif token == ')':
                top = operandStack.pop()
                while top != '(':
                    postfixList.append(top)
                    top = operandStack.pop()
            else:
                while (operandStack.is_empty() == False) and (
                        precedence[operandStack.peek()] >= precedence[token]
                        and token != "^"):
                    postfixList.append(operandStack.pop())
                operandStack.push(token)
    while operandStack.is_empty() == False:
        postfixList.append(operandStack.pop())
    return " ".join(postfixList)
예제 #3
0
def infix_to_postfix(infix_expr):
	#   converts infix expression to a postfix expression
    """ Method to convert infix expressions into postix
    Infix expression should have operations and operands seperated by spaces
    postfix expression will be formatted that way"""
    expression = infix_expr.split(" ")
    # operands = StackArray(len(expression)//2)
    operands = StackArray(30)
    to_process = []
    for part in expression:
        # part = expression[i]
        if not check_num(part):
            if (part == ')'):
                while (operands.peek() != '('):
                    to_process.append(str(operands.pop()))
                operands.pop()
                # print("Operand: " + part);
            else:
                while (not operandOnTop(part, operands)):
                    to_process.append(str(operands.pop()))
                operands.push(part);
                # print("Operand: " + part);
        else:
            if check_float(part):
                to_process.append(float(part))
            else:
                to_process.append(int(part))
    while (not operands.is_empty()):
        to_process.append(str(operands.pop()))
    postfix_expr = " ".join(str(thing) for thing in to_process)
    # print("Postfix Expression Ready: " + postfix_expr)
    return postfix_expr
예제 #4
0
def infix_to_postfix(infixexpr):
	"""Converts an infix expression to an equivalent postfix expression """

	"""Signature:  a string containing an infix expression where tokens are space separated is
	   the single input parameter and returns a string containing a postfix expression
	   where tokens are space separated"""
	
	newStack = StackArray(30)
	postfixList= []
	tokenList = infixexpr.split()
	x = 0
	par = 0 
	while x < len(tokenList): 
		if tokenList[x] is ('('): #When encountering paranthesis in the input
			newStack.push(tokenList[x])
			par = x+1
			while par < len(tokenList) and tokenList[par] not in (')'):
				if tokenList[par] not in ('*','-','/','+','^','('):
					postfixList.append(tokenList[par])
				elif tokenList[par] in ('('):
					newStack.push(tokenList[x])
				elif tokenList[par] in ('^'):
					if newStack.peek() in ('('):
						newStack.push(tokenList[par])
					elif newStack.peek() in '^':
						newStack.push(tokenList[par])
					elif newStack.peek() in ('*','/'):
						newStack.push(tokenList[par])
					elif newStack.peek() in ('+','-'):
						newStack.push(tokenList[par])
				elif tokenList[par] in ('*','/'):
					if newStack.peek() in ('('):
						newStack.push(tokenList[par])
					elif newStack.peek() in ('^'):
						postfixList.append(newStack.pop())
						newStack.push(tokenList[par])
					elif newStack.peek() in ('+','-'):
						newStack.push(tokenList[par])
					elif newStack.peek() in ('*','/'):
						postfixList.append(newStack.pop())
						newStack.push(tokenList[par])
				elif tokenList[par] in ('+','-'):
					if newStack.peek() in ('('):
						newStack.push(tokenList[par])
					elif newStack.peek() in ('^','*','/'):
						while newStack.peek() in ('^','*','/') and newStack.peek() not in ('(') :
							postfixList.append(newStack.pop())
						newStack.push(tokenList[par])
					elif newStack.peek() in ('+','-'):
						while newStack.peek() in ('+','-'):
							postfixList.append(newStack.pop())
						newStack.push(tokenList[par])
				par+=1
			condition = True
			while condition: #Popping and appending remaining symbols to list
				while newStack.peek() not in ('('):
					postfixList.append(newStack.pop())
				newStack.pop() #Removing the ( that was pushed onto the Stack
				iterate = 0
				if newStack.size() == 0:
						condition = False
						
				while iterate < newStack.size():
					if newStack.items[iterate] == None:
						iterate+=1
						continue
					elif newStack.items[iterate] in ('('):
						condition = True
						break
					else:
						iterate+=1	
					condition = False


				
			x = par

					 
		
		elif tokenList[x] not in ('*','-','/','+','^','(',')'): #Encountering a non paranthesis
			postfixList.append(tokenList[x])
		elif tokenList[x] in ('^'):
			if newStack.is_empty():
				newStack.push(tokenList[x])
			elif newStack.peek() in '^':
				newStack.push(tokenList[x])
			elif newStack.peek() in ('*','/'):
				newStack.push(tokenList[x])
			elif newStack.peek() in ('+','-'):
				newStack.push(tokenList[x])
		elif tokenList[x] in ('*','/'):
			if newStack.is_empty():
				newStack.push(tokenList[x])
			elif newStack.peek() in ('^'):
				postfixList.append(newStack.pop())
				newStack.push(tokenList[x])
			elif newStack.peek() in ('+','-'):
				newStack.push(tokenList[x])
			elif newStack.peek() in ('*','/'):
				postfixList.append(newStack.pop())
				newStack.push(tokenList[x])
		elif tokenList[x] in ('+','-'):
			if newStack.is_empty():
				newStack.push(tokenList[x])
			elif newStack.peek() in ('^','*','/'):
				while newStack.peek() in ('^','*','/') or not newStack.is_empty():
					postfixList.append(newStack.pop())
				newStack.push(tokenList[x])
			elif newStack.peek() in ('+','-'):
				while newStack.peek() in ('+','-'):
					postfixList.append(newStack.pop())
				newStack.push(tokenList[x])
		x+=1
	while not newStack.is_empty(): #Popping and appending remaining symbols to list
		postfixList.append(newStack.pop())
	return " ".join(postfixList) #Creates the Postfix Expression by joining the list