Ejemplo n.º 1
0
def parse_num(list):
    no_operator = re.split(r'[(+)notandor]', list)
    no_operator = [i for i in no_operator if i != '']
    no_operand = re.split(r'[0123456789]', list)
    no_oper = []
    parsed = []
    p = Stack()
    count = 0
    for i in range(len(no_operand)):
        if no_operand[i] == "(":
            p.push(no_operand[i])
        if no_operand[i] in ['+', '-', '*', '/', ')', 'not', 'and', 'or']:
            if p.peek() != '':
                p.push('')
                p.push(no_operand[i])
            else:
                p.push(no_operand[i])
        if no_operand[i] == '':
            if p.peek() != '':
                p.push('')

    no_oper = p.items

    for i in range(len(no_oper)):
        if no_oper[i] != '':
            parsed.append(no_oper[i])
        else:
            parsed.append(no_operator[count])
            count += 1
    return parsed
Ejemplo n.º 2
0
def infixToPostfix(infixexpr):
	prec = {'^': 4, '*': 3, '/': 3, '+': 2, '-': 2, '(': 1}
	opStack = Stack()
	postfixList = []
	tokenList = infixexpr.split()

	for token in tokenList:
		if token in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' or token in '1234567890':
			postfixList.append(token)

		elif token == '(':
			opStack.push('(')
		elif token == ')':
			topToken = opStack.pop()
			while topToken != '(':
				postfixList.append(topToken)
				topToken = opStack.pop()
		else:
			while (not opStack.isEmpty() ) and (prec[opStack.peek()] >= prec[token]):
				postfixList.append(opStack.pop())
			opStack.push(token)

	while not opStack.isEmpty():
		postfixList.append(opStack.pop())
	return ''.join(postfixList)
def infix_to_postfix(infixexpr: str):
    prec = {}
    prec["."] = 2
    prec["|"] = 1
    prec["*"] = 3
    # prec["+"] = 2
    prec["(."] = 0
    opStack = Stack()
    postfixList = []
    tokenList = infixexpr.split()

    for token in tokenList:
        if token in "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890()":
            postfixList.append(token)
        elif token == '(.':
            opStack.push(token)
        elif token == ').':
            topToken = opStack.pop()
            while topToken != '(.':
                postfixList.append(topToken)
                topToken = opStack.pop()
        else:
            while (not opStack.isEmpty()) and \
                    (prec[opStack.peek()] >= prec[token]):
                postfixList.append(opStack.pop())
            opStack.push(token)

    while not opStack.isEmpty():
        postfixList.append(opStack.pop())
    return " ".join(postfixList)
Ejemplo n.º 4
0
def infixToPostfix(infixexpr):
    prec = {}
    prec["*"] = 2  # changed priority of */ to 2. Was originally 3.
    prec["/"] = 2  # changed priority of */ to 2. Was originally 3.
    prec["+"] = 3  # changed priority of +- to 3. Was originally 2.
    prec["-"] = 3  # changed priority of +- to 3. Was originally 2.
    prec["("] = 1
    opStack = Stack()
    postfixList = []
    tokenList = infixexpr.split()

    for token in tokenList:
        if token in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or token in "0123456789":
            postfixList.append(token)
        elif token == '(':
            opStack.push(token)
        elif token == ')':
            topToken = opStack.pop()
            while topToken != '(':
                postfixList.append(topToken)
                topToken = opStack.pop()
        else:
            while (not opStack.isEmpty()) and \
               (prec[opStack.peek()] >= prec[token]):
                postfixList.append(opStack.pop())
            opStack.push(token)

    while not opStack.isEmpty():
        postfixList.append(opStack.pop())
    return " ".join(postfixList)
Ejemplo n.º 5
0
def infixToPostfix(infixexpr):
    prec = {}
    prec["@"] = 4
    prec["#"] = 4
    prec["&"] = 3
    prec["|"] = 2
    prec["("] = 1
    opStack = Stack()
    postfixList = []
    tokenList = infixexpr.split()

    for token in tokenList:
        if token not in "@#&|()":
            postfixList.append(token)
        elif token == '(':
            opStack.push(token)
        elif token == ')':
            topToken = opStack.pop()
            while topToken != '(':
                postfixList.append(topToken)
                topToken = opStack.pop()
        else:
            while (not opStack.isEmpty()) and \
               (prec[opStack.peek()] > prec[token]):
                postfixList.append(opStack.pop())
            opStack.push(token)

    while not opStack.isEmpty():
        postfixList.append(opStack.pop())
    return "".join(postfixList)
Ejemplo n.º 6
0
def infixToPostfix(infixexpr):
    prec = {}
    prec["*"] = 3
    prec["/"] = 3
    prec["+"] = 2
    prec["-"] = 2
    prec["("] = 1
    opStack = Stack()
    postfixList = []
    tokenList = infixexpr.split()

    for token in tokenList:
        if token in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or token in "0123456789":
            postfixList.append(token)
        elif token == '(':
            opStack.push(token)
        elif token == ')':
            topToken = opStack.pop()
            while topToken != '(':
                postfixList.append(topToken)
                topToken = opStack.pop()
        else:
            while (not opStack.isEmpty()) and \
               (prec[opStack.peek()] >= prec[token]):
                  postfixList.append(opStack.pop())
            opStack.push(token)

    while not opStack.isEmpty():
        postfixList.append(opStack.pop())
    return " ".join(postfixList)
Ejemplo n.º 7
0
    def infix_to_postfix(self, infixexpr):
        opStack = Stack()
        postfixList = []
        tokenList = infixexpr.split()

        for token in tokenList:
            if BoolParser.isBoolVariable(token):
                # if token is a boolean variable, just append to list
                postfixList.append(token)
            elif token == '(':
                # start a new nested expression in the stack
                opStack.push(token)
            elif token == ')':
                # end the nested expression by moving the operators
                # from the stack to the list (i.e. in reverse order)
                topToken = opStack.pop()
                while topToken != '(':
                    postfixList.append(topToken)
                    topToken = opStack.pop()
            else:
                while (not opStack.isEmpty()) and \
                   (BoolParser.PREC[opStack.peek()] >= BoolParser.PREC[token]):
                    postfixList.append(opStack.pop())
                opStack.push(token)

        while not opStack.isEmpty():
            postfixList.append(opStack.pop())

        return postfixList
Ejemplo n.º 8
0
def infixToPostfix(infixexpr):
    prec = {'*': 3, '/': 3, '+': 2, '-': 2, '(': 1, '^': 4}
    postfixList = []
    opStack = Stack()

    tokenList = infixexpr.split()
    for token in tokenList:
        if token in string.uppercase or token.isdigit():
            postfixList.append(token)
        elif token == '(':
            opStack.push(token)
        elif token == ')':
            top = opStack.pop()
            while top != '(':
                postfixList.append(top)
                top = opStack.pop()
        else:
            while not opStack.isEmpty() and prec[opStack.peek()] >= prec[token]:
                postfixList.append(opStack.pop())
            opStack.push(token)

    while not opStack.isEmpty():
        postfixList.append(opStack.pop())

    return " ".join(postfixList)
Ejemplo n.º 9
0
def infixToPostfix(infixexpr):
    prec = {}
    prec["*"] = 3
    prec["/"] = 3
    prec["+"] = 2
    prec["-"] = 2
    prec["("] = 1
    opStack = Stack()
    postfixList = []
    tokenList = infixexpr.split()

    for token in tokenList:
        if token not in prec.keys(
        ) and token != ')':  #token in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or token in "0123456789":
            postfixList.append(token)
        elif token == '(':
            opStack.push(token)
        elif token == ')':
            topToken = opStack.pop()
            while topToken != '(':
                postfixList.append(topToken)
                topToken = opStack.pop()
        else:
            while (not opStack.isEmpty()) and \
               (prec[opStack.peek()] >= prec[token]):
                postfixList.append(opStack.pop())
            opStack.push(token)

    while not opStack.isEmpty():
        postfixList.append(opStack.pop())
    return " ".join(postfixList)
def infixToPostfix(expr):
    opStack = Stack()
    exprPref = {}
    exprPref['^'] = 4
    exprPref['/'] = 3
    exprPref['*'] = 3
    exprPref['+'] = 2
    exprPref['-'] = 2
    exprPref['('] = 1
    postFixExpr = []
    expr = expr.split()
    for token in expr:
        if token in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or token in "1234567890":
            postFixExpr.append(token)
        elif token == '(':
            opStack.push(token)
        elif token == ')':
            top = opStack.pop()
            while top != '(':
                postFixExpr.append(top)
                top = opStack.pop()
        else:
            while not opStack.isEmpty() and exprPref[opStack.peek()] >= exprPref[token]:
                postFixExpr.append(opStack.pop())
            opStack.push(token)

    while not opStack.isEmpty():
        postFixExpr.append(opStack.pop())
    
    return " ".join(postFixExpr)
Ejemplo n.º 11
0
def infixToPostfix(infixexpr):
   prec = {}
   prec["^"] = 4
   prec["*"] = 3
   prec["/"] = 3
   prec["+"] = 2
   prec["-"] = 2
   prec["("] = 1
   opStack = Stack()
   postfixList = []
   tokenList = infixexpr.split()

   for token in tokenList:
      if token in string.ascii_uppercase or token in string.digits:
         postfixList.append(token)
      elif token == "(":
         opStack.push(token)
      elif token == ")":
         topToken = opStack.pop()
         while topToken != "(":
            postfixList.append(topToken)
            topToken = opStack.pop()

      else:
         while (not opStack.isEmpty()) and (prec[opStack.peek()] >= prec[token]):
            postfixList.append(opStack.pop())
         opStack.push(token)

   while not opStack.isEmpty():
      postfixList.append(opStack.pop())
   return " ".join(postfixList)
Ejemplo n.º 12
0
def infixToPostfix(infixexpr):  # fix this code to do floats
    prec = {}
    prec["*"] = 3
    prec["/"] = 3
    prec["+"] = 2
    prec["-"] = 2
    prec["("] = 1
    opStack = Stack()
    postfixList = []
    tokenList = infixexpr.split()
    alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

    for token in tokenList:
        if token in alphabet:
            postfixList.append(token)
        elif isfloat(token):
            postfixList.append(token)
        elif token == '(':
            opStack.push(token)
        elif token == ')':
            topToken = opStack.pop()
            while topToken != '(':
                postfixList.append(topToken)
                topToken = opStack.pop()
        else:
            while (not opStack.isEmpty()) and \
               (prec[opStack.peek()] >= prec[token]):
                  postfixList.append(opStack.pop())
            opStack.push(token)

    while not opStack.isEmpty():
        postfixList.append(opStack.pop())
    return " ".join(postfixList)
Ejemplo n.º 13
0
def infix_to_postfix(infix_str):
    prec = {"*": 3, "/": 3, "+": 2, "-": 2, "(": 1}
    op_stack = Stack()
    postfix_list = []
    token_list = infix_str.split()
    print(token_list)
    for token in token_list:
        if token in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' or token in "0123456789":
            postfix_list.append(token)
        elif token == '(':
            op_stack.push(token)
        elif token == ')':
            top_token = op_stack.pop()
            while top_token != '(':
                postfix_list.append(top_token)
                top_token = op_stack.pop()
        else:
            while (not op_stack.isEmpty()) and \
                    (prec[op_stack.peek()] >= prec[token]):
                postfix_list.append(op_stack.pop())
            op_stack.push(token)

    while not op_stack.isEmpty():
        postfix_list.append(op_stack.pop())
    return postfix_list
Ejemplo n.º 14
0
def infix_to_postfix(query):
    query_list = word_tokenize(query)

    stack = Stack()
    postfix = []

    for word in query_list:
        if word not in OPERATORS:
            postfix.append(word)
        elif word == '(':
            stack.push(word)
        elif word == ')':
            top = stack.pop()
            while top != '(':
                postfix.append(top)
                top = stack.pop()
        else:
            while not stack.isEmpty() and PRECIDENT[
                    stack.peek()] >= PRECIDENT[word]:
                postfix.append(stack.pop())
            stack.push(word)

    while not stack.isEmpty():
        postfix.append(stack.pop())
    return ' '.join(postfix)
def infixToPostfix(infixexpr):
    prec = {}
    prec['*'] = 3
    prec['/'] = 3
    prec['+'] = 2
    prec['-'] = 2
    prec['('] = 1
    opStack = Stack()
    postfixList = []
    tokenList = infixexpr.split()

    for token in tokenList:
        if token in 'ABCDEFGHIJKLMNOPQRSTUMWXYZ' or token in '0123456789':
            postfixList.append(token)
        elif token == '(':
            opStack.push(token)
        elif token == ')':
            topToken = opStack.pop()
            while topToken != '(':
                postfixList.append(topToken)
                topToken = opStack.pop()
        else:
            while (not opStack.isEmpty()) and (prec[opStack.peek()] >= prec[token]):
                postfixList.append(opStack.pop())
            opStack.push(token)

    while not opStack.isEmpty():
        postfixList.append(opStack.pop())

    return ' '.join(postfixList)
 def infix_to_postfix(self, infixexpr):
     opStack = Stack()
     postfixList = []
     tokenList = infixexpr.split()
     
     for token in tokenList:
         if BoolParser.isBoolVariable(token):
             # if token is a boolean variable, just append to list
             postfixList.append(token)
         elif token == '(':
             # start a new nested expression in the stack
             opStack.push(token)
         elif token == ')':
             # end the nested expression by moving the operators
             # from the stack to the list (i.e. in reverse order)
             topToken = opStack.pop()
             while topToken != '(':
                 postfixList.append(topToken)
                 topToken = opStack.pop()
         else:
             while (not opStack.isEmpty()) and \
                (BoolParser.PREC[opStack.peek()] >= BoolParser.PREC[token]):
                   postfixList.append(opStack.pop())
             opStack.push(token)
 
     while not opStack.isEmpty():
         postfixList.append(opStack.pop())
     
     return postfixList
Ejemplo n.º 17
0
def query_processing(user_query):
    '''Query processing: 1. transform infix format to postfix format;
                            ref: https://bit.ly/28OMA5X
                         2. deal with the wildcard '''
    # Split the query into a list of word, including the parentheses
    pattern = re.compile(r"([.()!])")
    tmp = (pattern.sub(" \\1 ", user_query)).split(" ")
    tokenList = list(filter(None,tmp))

    # Transform infix to postfix
    opStack = Stack()
    postfixList = []
    prec = {}
    prec["("] = 1
    prec["AND"] = 2
    prec["OR"] = 2
    prec["AND_NOT"] = 2
    for t in tokenList:
        if (not(isOperator(t))):
            postfixList.append(t)
        elif t == "(":
            opStack.push(t)
        elif t == ")":
            topToken = opStack.pop()
            while topToken != "(":
                postfixList.append(topToken)
                topToken = opStack.pop()
        else:
            while (not opStack.isEmpty()) and  (prec[opStack.peek()] >= prec[t]):
                postfixList.append(opStack.pop())
            opStack.push(t)

    while (not opStack.isEmpty()):
        postfixList.append(opStack.pop())
    return " ".join(postfixList)
Ejemplo n.º 18
0
def infixToPostfix(infixexpr):
    prec = {}
    prec["*"] = 3
    prec["/"] = 3
    prec["+"] = 2
    prec["-"] = 2
    prec["("] = 1

    opStack = Stack()
    postfixList = []
    tokenList = infixexpr.split()

    for token in tokenList:
        # 如果标记是操作数,将其附加到列表的结尾
        if token in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or token in "0123456789":
            postfixList.append(token)
        # 如果标记是左括号,将其压入栈中
        elif token == "(":
            opStack.push(token)
        # 如果标记是右括号, 要弹出栈中的运算符, 直到遇到左括号为止, 并把弹出的运算符加到列表最后
        elif token == ")":
            topToken = opStack.pop()
            while topToken != "(":
                postfixList.append(topToken)
                topToken = opStack.pop()
        # 如果是+ - * /运算符, 将其压入栈中之前, 要先判断有没有比它运算等级更先或相等的运算符, 有的话要先把这些加到输出列表结尾
        else:
            while (not opStack.isEmpty()) and (prec[opStack.peek()] >= prec[token]):
                postfixList.append(opStack.pop())
            opStack.push(token)

    while not opStack.isEmpty():
        postfixList.append(opStack.pop())

    return " ".join(postfixList)
Ejemplo n.º 19
0
def inToPostfix(expression):
	expression = expression.replace(" ","")
	open_count = 0
	closed_count = 0
	new_exp = []
	numeric_buffer = []
	prev = ''
	for each in expression:
		if each not in "1234567890+-/()*":
			print("invalid expression")
			return "invalid syntax"
		if prev in "+-*/" and each in "+-*/":
			print("invalid expression")
			return "invalid syntax"
		if each in "+-()*/":
			if each == "(":
				open_count+=1
			if each == ")":
				closed_count+=1
			if numeric_buffer!=[]:
				new_exp.append(int(''.join(numeric_buffer)))
			numeric_buffer = []
			new_exp.append(each)
		else:
			numeric_buffer.append(each)
		prev = each
	if open_count!=closed_count:
		print("brackets mismatch")
		return "invalid syntax"
	if numeric_buffer!=[]:
		new_exp.append(int(''.join(numeric_buffer)))
	expression = new_exp
	print("INFIX: " +str(expression))

	dict_exp = {'/':4, '*':3, '+':2, '-':1, '(':0}

	operations = Stack()
	output = []

	for ch in expression:
		if ch=='(':
			operations.push(ch)
		elif type(ch)==int:
			output.append(ch)
		elif ch==')':
			chMain = operations.pop()
			while chMain!='(':
				output.append(chMain)
				chMain = operations.pop()
		else:
			while(not operations.isEmpty()) and (dict_exp[operations.peek()]\
				>= dict_exp[ch]):
				output.append(operations.pop())
			operations.push(ch)

	while not operations.isEmpty():
		output.append(operations.pop())

	return output
def sortstacks(astack):
     temp=Stack()
     while not astack.isEmpty():
          tmp=astack.pop()
          while temp.peek()<tmp:
               temp.pop()
          temp.push(tmp)
     return temp
Ejemplo n.º 21
0
def infixToPrefix(infixexpr):
    ##记录操作符的优先级
    prec = {}

    prec["*"] = 3
    prec["/"] = 3
    prec["+"] = 2
    prec["-"] = 2
    prec["("] = 1
    opStack = Stack()
    prefixList = []
    tokenList = reversed(infixexpr.split())  ###:反转,来实现从右到左的扫描

    for token in tokenList:

        ##如果扫描是操作数,将其附加输出到列表末尾
        if token in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or token in "0123456789":
            prefixList.append(token)

        ##如果是右括号,将其压倒opStack上
        elif token == ')':
            opStack.push(token)

        ##如果标记是左括号,则弹出 s,直到删除相应的右括号。将每个运算符附加到输出列表的末尾
        elif token == '(':
            while opStack.seek() != ')':
                prefixList.append(opStack.pop())
            opStack.pop()

        # 如果标记是运算符, *,/,+  或  -  ,将其压入 s。
        # 但是,首先删除已经在s中具有更高或相等优先级的任何运算符,并将它们加到输出列表中
        else:
            while (not opStack.isEmpty()) and \
                (opStack.peek() != ')') and \
                (prec[opStack.peek()] > prec[token]):
                prefixList.append(opStack.pop())
            opStack.push(token)
    # 当输入表达式被完全处理时,检查 s。
    # 仍然在栈上的任何运算符都可以删除并加到输出列表的末尾
    while not opStack.isEmpty():
        prefixList.append(opStack.pop())

    #反转序列
    prefixList.reverse()
    return "".join(prefixList)
Ejemplo n.º 22
0
def infixToPostfix(infixexpr):
    prec = {}
    prec["*"] = 3
    prec["/"] = 3
    prec["+"] = 2
    prec["-"] = 2
    prec["("] = 1
    opStack = Stack()
    postfixList = []
    tokenList = []
    tokenListAux = infixexpr.split()

    for t in tokenListAux:
        flag = 0
        if (not (t == "")):
            if ((t.startswith("(") and t != "(")
                    or (t.endswith(")") and t != ")")):
                if (t.startswith("(") and t != "("):
                    t = t.replace("(", '')
                    tokenList.append("(")
                    if (t.endswith(")") and t != ")"):
                        t = t.replace(")", '')
                        tokenList.append(t)
                        tokenList.append(')')
                        flag = 1
                    else:
                        tokenList.append(t)

                if (t.endswith(")") and t != ")"):
                    t = t.replace(")", '')
                    if (flag == 0):
                        tokenList.append(t)

                    tokenList.append(")")
            else:
                tokenList.append(t)

    for token in tokenList:
        if (token != "*" and token != "/" and token != "+" and token != "-"
                and token != "(" and token != ")"):
            postfixList.append(token)
        elif token == '(':
            opStack.push(token)
        elif token == ')':
            topToken = opStack.pop()
            while topToken != '(':
                postfixList.append(topToken)
                topToken = opStack.pop()
        else:
            while (not opStack.isEmpty()) and (prec[opStack.peek()] >=
                                               prec[token]):
                postfixList.append(opStack.pop())
            opStack.push(token)

    while not opStack.isEmpty():
        postfixList.append(opStack.pop())
    return " ".join(postfixList)
Ejemplo n.º 23
0
class Conversion (object) :
    
    def __init__(self):
        self.prec = {}
        self.init_prec()
        self.op_stack = Stack() #operators will be kept in this stack
        self.output_list = []   #any postfix or prefix expression will be written in the list
        self.token_list = [] #initial expression will be read and kept in this list    
        self.operands = []
        self.init_operand()
        
    def init_prec(self) :
        self.prec["*"] = 3
        self.prec["/"] = 3
        self.prec["+"] = 2
        self.prec["-"] = 2
        self.prec["("] = 1
    
    def init_operand(self) :
        self.operands = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "0123456789"
    
    def re_init(self) :
        #After any operation, the stack should be empty
        self.op_stack = Stack()
        self.output_list = []
        self.token_list = []

    def infixToPostfix(self,infixexpr) :
        '''The function will read an infix expression and write its 
        corresponding expression in the output_list
        doesn't return anything but alters the output_list'''
        self.re_init()
        self.token_list = infixexpr.split()
        for token in self.token_list :
            if token in self.operands :
                self.output_list.append(token)
            elif token == '(' :
                self.op_stack.push(token)
            elif token == ')' :
                top_token = self.op_stack.pop()
                while top_token != '(' :
                    self.output_list.append(top_token)
                    top_token = self.op_stack.pop()
            else :
                while (not self.op_stack.isEmpty()) and \
                    (self.prec[self.op_stack.peek()] >= self.prec[token]) :
                    self.output_list.append(self.op_stack.pop())
                self.op_stack.push(token)    
        while not self.op_stack.isEmpty() :
            self.output_list.append(self.op_stack.pop())             
    
    def getOutput(self) :
        return " ".join(self.output_list)

    def infixToPrefix(self, infixexpr) :
        pass
Ejemplo n.º 24
0
 def f_to_m(cur_list):  # 前转中缀
     """
     :cur_list: list
     """
     temp = []
     temp2 = []
     s = Stack()
     list = [str(i) for i in cur_list]
     print(list)
     for par in list:
         if par in "+-*/":  # 遇到运算符则入栈
             s.push(par)
         else:  # 为数字时分两种情况:
             if s.peek() in '+-*/':  # 栈顶为运算符
                 s.push(par)  # 数字入栈
             else:  # 当前栈顶为数字
                 while (not s.isEmpty()) and (
                         not s.peek() in '+-*/'):  # 若栈不空,且当前栈顶为数字,则循环计算
                     shu = s.pop()  # 运算符前的数字出栈
                     fu = s.pop()  # 运算符出栈
                     if fu == '+' or fu == '-':
                         if s.size() == 0:  # 最后一次运算不需要括号,无论什么运算符
                             par = shu + fu + par
                             break
                         par = '(' + shu + fu + par + ')'  # 计算
                     else:  # 乘除不需要括号
                         par = shu + fu + par  # 计算
                 s.push(str(par))  # 算式入栈
     list1 = (str(s.pop()))  # 用列表存新的算式
     for i in list1:
         if i in '+-*/()':
             if len(temp2) == 0:
                 temp.append(i)
             else:
                 temp.append(int(''.join(temp2)))
                 temp2.clear()
                 temp.append(i)
         else:
             temp2.append(i)
     if len(temp2) != 0:
         temp.append(int(''.join(temp2)))
     return temp  # 返回最终算式
Ejemplo n.º 25
0
def infix_to_prefix(infix_expr):
    prec = dict()
    prec[")"] = 4
    prec["*"] = 3
    prec["/"] = 3
    prec["+"] = 2
    prec["-"] = 2
    prec["("] = 1
    prefix_expr = []
    s = Stack()
    # 从右到左扫描
    for item in reversed(infix_expr.split()):
        # 如果标记是操作数,将其附加到输出列表的末尾
        if item not in prec.keys():
            prefix_expr.append(item)
        # 如果标记是右括号,将其压到 s 上
        elif item == ')':
            s.push(item)
        # 如果标记是左括号,则弹出 s,直到删除相应的右括号。将每个运算符附加到
        # 输出列表的末尾
        elif item == '(':
            while s.peek() != ')':
                prefix_expr.append(s.pop())
            s.pop()
        # 如果标记是运算符, *,/,+  或  -  ,将其压入 s。但是,首先删除已经在
        # s 中具有更高或相等优先级的任何运算符,并将它们加到输出列表中
        else:
            while (not s.is_empty()) \
                    and s.peek() != ')' \
                    and prec[s.peek()] > prec[item]:
                prefix_expr.append(s.pop())
                s.push(item)
            s.push(item)
        # print(s.items)
    # 当输入表达式被完全处理时,检查 s。仍然在栈上的任何运算符都可以删除并加到
    # 输出列表的末尾
    while not s.is_empty():
        prefix_expr.append(s.pop())
    # 反转序列
    prefix_expr.reverse()
    return ' '.join(prefix_expr)
Ejemplo n.º 26
0
def postFix(mystr):
    prec = {}
    prec["**"] = 4
    prec["*"] = 3
    prec["/"] = 3
    prec["+"] = 2
    prec["-"] = 2
    prec["("] = 1
    opstack = Stack()
    operator = "+-*/"
    powop = "**"
    parens = "()"
    outList = []
    mystr = mystr.split()
    print(mystr)
    for thing in mystr:
        if thing in operator or thing == powop:
            if opstack.isEmpty():
                opstack.push(thing)
            else:
                precCurr = prec[thing]
                precOld = prec[opstack.peek()]
                while not opstack.isEmpty() and prec[
                        opstack.peek()] >= prec[thing]:
                    outList.append(opstack.pop())
                opstack.push(thing)
        elif thing in parens:
            if thing == parens[0]:
                opstack.push(thing)
            else:
                ii = opstack.pop()
                while ii != "(":
                    outList.append(ii)
                    ii = opstack.pop()
        else:
            outList.append(thing)
        # print(thing,"Loop ended",sep=": ")
    while not opstack.isEmpty():
        outList.append(opstack.pop())
    return outList
Ejemplo n.º 27
0
    def calculator(self, data):
        self.s = data
        opstack = Stack()

        splitdata = self.s.split()
        postfix = list()
        for i in splitdata:
            if i in "0123456789":
                postfix.append(i)
            elif i == '(':
                opstack.push(i)
            elif i == ')':
                topToken = opstack.pop()
                while topToken != '(':
                    postfix.append(topToken)
                    topToken = opstack.pop()
            else:
                while (not opstack.isEmpty()) and \
                    (self.prec[opstack.peek()] >= self.prec[i]):
                    postfix.append(opstack.pop())
                    print("here")
                opstack.push(i)

        while not opstack.isEmpty():
            postfix.append(opstack.pop())
        opstack = Stack()
        operandList = list()
        print(postfix)
        for token in postfix:
            if token in "123456789":
                opstack.push(token)
            elif token == "*":
                i = opstack.pop()
                j = opstack.pop()
                resultdata = float(i) * float(j)
                opstack.push(resultdata)
            elif token == "+":
                i = opstack.pop()
                j = opstack.pop()
                resultdata = float(i) + float(j)
                opstack.push(resultdata)
            elif token == "-":
                i = opstack.pop()
                j = opstack.pop()
                resultdata = float(j) - float(i)
                opstack.push(resultdata)
            elif token == "/":
                i = opstack.pop()
                j = opstack.pop()
                resultdata = float(j) / float(i)
                opstack.push(resultdata)
        return opstack.pop()
Ejemplo n.º 28
0
def postfix_converter(exp):
	exp = ['('] + exp + [')']
	#print(exp)
	i = 0
	operator_stack = Stack()

	postfix_exp = []
	while(i < len(exp)):
		if (exp[i] in numbers):
			postfix_exp.append(exp[i])


		if (exp[i] == '('):
			operator_stack.push(exp[i])


		if (exp[i] == ')'):
			while (operator_stack.peek() != '('):
				postfix_exp.append(operator_stack.pop())
			operator_stack.pop()



		if (exp[i] in precedence_dict.keys()):
			if (operator_stack.peek() == '('):
				operator_stack.push(exp[i])


			elif (precedence_dict[exp[i]] < precedence_dict[operator_stack.peek()]):
				operator_stack.push(exp[i])

			else:
				postfix_exp.append(exp[i])
				postfix_exp.append(operator_stack.pop())



		i += 1
	return postfix_exp
Ejemplo n.º 29
0
def test_stack():
    s = Stack()
    print(s.is_empty())
    s.push(4)
    s.push('dog')
    print(s.peek())
    s.push(True)
    print(s.size())
    print(s.is_empty())
    s.push(8.4)
    print(s.pop())
    print(s.pop())
    print(s.size())
Ejemplo n.º 30
0
def calculator(str):
    expression = []  #list
    numbers = []
    operator = Stack()  #stack
    ranking = {'+': 1, '-': 1, '*': 2, '/': 2}
    middle_num = 0
    right_num = 0
    left_num = 0

    # 담기
    #숫자 : 배열에 넣기
    #기호(맨 위 연산자보다 우선순위가 낮거나 같을 때 ) : 기존 값들을 배열에, 본인은 스택에
    #기호(우선순위 높을 때) : 스택에 본인 값 저장
    for s in str:
        if s.isdigit():
            expression.append(s)
        elif s in ranking.keys():
            if len(operator) == 0:
                operator.append(s)
            elif ranking[s] <= ranking[operator.peek()]:
                while operator:
                    expression.append(operator.pop())
                operator.push(s)
            else:
                operator.push(s)

    # 남은 기호들 배열에 넣기
    while operator:
        expression.append(operator.pop())

    # 계산하기
    for e in expression:
        if e.isdigit():
            numbers.push(e)
        else:
            right_num = int(numbers.pop())
            left_num = int(numbers.pop())
            if e == '+':
                middle_num = left_num + right_num
            elif e == '-':
                middle_num = left_num - right_num
            elif e == '*':
                middle_num = left_num * right_num
            elif e == '/':
                middle_num = left_num / right_num

            numbers.push(middle_num)

    return numbers.pop()
Ejemplo n.º 31
0
def xiaoxiaole(s):
    st = Stack()
    for a in s:
        if not st.isEmpty() and a == st.peek():
            st.pop()
        else:
            st.push(a)
    if st.isEmpty():
        return None
    else:
        output = ''
        while not st.isEmpty():
            output = output + str(st.pop())
        o = output[::-1]
        return o
def balanced(inputStr):
    opeStack = Stack()
    balanced = True
    for char in inputStr:
        if char in "({[<":
            opeStack.push(char)
        else:
            if opeStack.isEmpty() or (not matches(opeStack.peek(), char)):
                balanced = False
                return balanced
            opeStack.pop()

    if not opeStack.isEmpty():
        balanced = False
    return balanced
Ejemplo n.º 33
0
def infix_to_post(str):
	tokenList = str.split()
	length = len(tokenList)
	
	cnt_pa = 0
	cnt_op = 0
	for token in tokenList:
		if token not in "ABCDEFGHIJKLMNOPQRST" and token not in "0123456789" and token not in "+-*/" and token not in "()":
			raise RunTimeError("Wrong input")
		if token in "()":
			count_pa += 1
		if token in "+-*/"
			count_op += 1
	if length - cnt_pa != 2 * cnt_op + 1:
		raise RunTimeError("Wrong input")



	opStack = Stack()
	postFixList = []
	prec = {}
	prec['('] = 1
	prec[')'] = 1
	prec['+'] = 2
	prec['-'] = 2
	prec['*'] = 3
	prec['/'] = 3

	for token in tokenList:
		if token in "ABCDEFGHIJKLMNOPQRST" or token in "0123456789":
			postFixList.append(token)

		elif token == "(":
			opStack.push(token)

		elif token == ")":
			topToken = opStack.pop()
			if topToken != "(":
				postFixList.append(topToken)
				topToken = opStack.pop()
		else:
			while not opStack.isEmpty() and prec[opStack.peek()] > prec[token]:
				postFixList.append(opStack.pop())
			opStack.push(token)
	while not opStack.isEmpty():
		postFixList.append(opStack.pop())

	return " ".join(postFixList)
Ejemplo n.º 34
0
def Xor(x):
    sum = 0
    i = 0
    s = ""
    bin = Stack()
    while x >= 1:
        bin_num = x % 2
        x = int(x / 2)
        bin.push(str(bin_num))
    while bin.isEmpty() == False:
        s = s + str(bin.peek())
        bin.pop()
    while i < len(s):
        if s[i] == "0":
            sum = sum + (2**(len(s) - i - 1))
        i = i + 1
    return sum
Ejemplo n.º 35
0
def infix_to_postfix(infix: str):
    """Takes an infix expression and converts it to postfix."""
    prec = {}  # dictionary to hold precedence of different values
    prec["*"] = 3
    prec["/"] = 3
    prec["+"] = 2
    prec["-"] = 2
    prec["("] = 1
    opStack = Stack()
    post_fix: list = []
    token: list = infix.split()

    try:
        for t in token:
            #  If the token we are on isn't an operator or (, add it to the postfix list
            # list because the position of the letters and numbers do not change.
            if t in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or t in "0123456789":
                post_fix.append(t)
            # If the token is a opening paren "(" it means there will be a closing
            # paren we need to translate this to postfix, pop it on the stack.
            elif t == "(":
                opStack.push(t)
            # if the token is a closing paren
            elif t == ")":
                top_token = opStack.pop()
                while top_token != "(":
                    post_fix.append(top_token)
                    top_token = opStack.pop()
            # If the token is an operator, check to see if the opstack is empty and if the
            # tokens precedence is > or = the top token on the stack.
            # if it's greater than, it will be calculated first, so put it in the list.
            else:
                while (not opStack.isEmpty()) and (prec[opStack.peek()] >=
                                                   prec[t]):
                    post_fix.append(opStack.pop())
                # if the stack is empty or the precedence is less than, put the token on the top of the stack.
                #  this way the lower precedence operators will get added to the list first.
                opStack.push(t)
        # after we've gone through all of the tokens, check the stack to see what is left.
        # pop it off in that order and add it to the list
        while not opStack.isEmpty():
            post_fix.append(opStack.pop())
        # join the list and return
        return " ".join(post_fix)
    except:
        print(f"Whoops, something went wrong. {infix} not valid.")
def convertToPostfix(infixStr):
    """This function converts a given infix string into
       a postfix string..

       >>> print(convertToPostfix("A * B + C * D"))
       A B * C D * +
       >>> print(convertToPostfix("( A + B ) * C - ( D - E ) * ( F + G )"))
       A B + C * D E - F G + * -
       >>> print(convertToPostfix("5 * 3 ^ ( 4 - 2 )"))
       5 3 4 2 - ^ *
    """

    prec = {}
    prec["^"], prec["**"] = 4, 4
    prec["*"] = 3
    prec["/"] = 3
    prec["+"] = 2
    prec["-"] = 2
    prec["("] = 1
    opStack = Stack()
    postfixList = []
    infixList = infixStr.split()
    correctData(infixList)

    for token in infixList:
        if len(token) > 1 and token.isalnum():
            postfixList.append(token)
            continue
        if token in "0123456789ABCDEFGHIJKLMNOPRSTUVWXYZ":
            postfixList.append(token)
        elif token == "(":
            opStack.push(token)
        elif token == ")":
            topToken = opStack.pop()
            while topToken != "(":
                postfixList.append(topToken)
                topToken = opStack.pop()
        else:
            while (not opStack.isEmpty()) and  \
            prec[opStack.peek()] >= prec[token]:
                postfixList.append(opStack.pop())
            opStack.push(token)
    while (not opStack.isEmpty()):
        postfixList.append(opStack.pop())
    postfixstr = " ".join(postfixList)
    return postfixstr
Ejemplo n.º 37
0
def dailyTemp(T):
    ans_list = []
    s = Stack()
    while abs(i) < len(T):
        if s.isEmpty() is True:
            s.push(i)
            ans_list[i] = 0
            i = i - 1
        else:
            if T[i] >= s.peek():
                s.pop()
                i = i - 1
            else:
                ans_list[i] = s.top() - i
                s.push(i)
                i = i - 1
    return ans_list
Ejemplo n.º 38
0
def infixToPostfix(infixepr):
	"""Create an empty stack called opstack for keeping operators. Create an empty list for output.
Convert the input infix string to a list by using the string method split.
Scan the token list from left to right.
If the token is an operand, append it to the end of the output list.
If the token is a left parenthesis, push it on the opstack.
If the token is a right parenthesis, pop the opstack until the corresponding left parenthesis is removed. Append each operator to the end of the output list.
If the token is an operator, *, /, +, or -, push it on the opstack. However, first remove any operators already on the opstack that have higher or equal precedence and append them to the output list.
When the input expression has been completely processed, check the opstack. Any operators still on the stack can be removed and appended to the end of the output list.
"""
	prec = {}
	prec["*"] = 3
	prec["/"] = 3
	prec["+"] = 2
	prec["-"] = 2
	prec["("] = 1

	opStack = Stack()

	postfixList = []
	tokenList = infixepr.split()

	for token in tokenList:
		  if token in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or token in "0123456789":
		  	postfixList.append(token)
		  elif token == '(':
		  	opStack.push(token)
		  elif token ==')':
		  	topToken = opStack.pop()
		  	while topToken != '(':
		  		postfixList.append(topToken)
		  		topToken = opStack.pop()

		  else:
		  	while (not opStack.isEmpty()) and (prec[opStack.peek()] >= prec[token]):
		  		postfixList.append(opStack.pop())

		  	opStack.push(token)


	while not opStack.isEmpty():
		postfixList.append(opStack.pop())

	return " ".join(postfixList)
Ejemplo n.º 39
0
    def __infix_to_postfix(infix_expr):
        """Преобразование из инфиксной формы в постфиксную"""
        prec = {"AND": 2, "OR": 1}  # приоритеты операций
        op_stack = Stack()
        post_fix_list = []
        token_list = infix_expr

        for token in token_list:
            if token not in ("AND", "OR"):
                post_fix_list.append(token)
            else:
                while (not op_stack.isEmpty()) and \
                        (prec[op_stack.peek()] >= prec[token]):
                    post_fix_list.append(op_stack.pop())
                op_stack.push(token)

        while not op_stack.isEmpty():
            post_fix_list.append(op_stack.pop())

        return post_fix_list
Ejemplo n.º 40
0
def xiaoxiaole(string):
    s = Stack()
    for index in range(len(string)):
        a = string[index]
        if s.isEmpty() or index == 0:
            s.push(a)
        else:
            if a != s.peek():
                s.push(a)
            else:
                s.pop()

    if s.isEmpty():
        return None
    else:
        output = ''
        while not s.isEmpty():
            output = output + str(s.pop())
            o = output[::-1]
        return o
def infixToPostfix(infixexpr):
    """
    @infixexpr 表达式,如: A * B, 每个字符之间必须空格
    """
    prec = {}
    prec["*"] = 3
    prec["/"] = 3
    prec["+"] = 2
    prec["-"] = 2
    prec["("] = 1
    opStack = Stack()
    postfixList = []
    tokenList = infixexpr.split()

    for token in tokenList:
        if token in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or token in "0123456789":
            postfixList.append(token)
            print('1======', postfixList)
        elif token == '(':
            opStack.push(token)
            print('2=======', opStack.isEmpty())
        elif token == ')':
            topToken = opStack.pop()
            while topToken != '(':
                postfixList.append(topToken)
                topToken = opStack.pop()
                print('3======', postfixList)
        else:  #当token = *时,
            while (not opStack.isEmpty()) and (prec[opStack.peek()] >=
                                               prec[token]):
                print('4=======', opStack.isEmpty())
                postfixList.append(opStack.pop())
            opStack.push(token)  # 将*加入栈中
            print('5======', postfixList)
            print('6=======', opStack.isEmpty())
    print('7======', postfixList)
    print('8=======', opStack.isEmpty())
    while not opStack.isEmpty():
        postfixList.append(opStack.pop())
    print('9======', postfixList)
    return " ".join(postfixList)
Ejemplo n.º 42
0
from pythonds.basic.stack import Stack

s = Stack()

assert(s.isEmpty())
s.push(4)
s.push('dog')
assert(s.peek() is 'dog')
s.push(True)
assert(s.size() is 3)
assert(s.isEmpty() is False)
s.push(8.4)
assert(s.pop() is 8.4)
assert(s.pop() is True)
assert(s.size() is 2)
Ejemplo n.º 43
0
from pythonds.basic.stack import Stack

s = Stack()

str = 'my python Script'

for i in range(len(str)):
	s.push(str[i])


mystr=''


while not s.isEmpty():
	mystr += s.peek()
	s.pop()

print mystr
Ejemplo n.º 44
0
'''
Created on Jul 11, 2015

@author: Krish
'''
from pythonds.basic.stack import Stack

s= Stack()

print(s.isEmpty())
s.push(4)
s.push('dog')
print(s.peek())
s.push(True)
print(s.size())
print(s.isEmpty())
s.push(8.4)
print(s.pop())
print(s.pop())
print(s.size())