Example #1
0
def infix_to_postfix(token_list):
    stack = Stack()
    postfix_list = []

    for token in token_list:
        if token.isalpha() or token.isdecimal():
            postfix_list.append(token)

        elif token == '(':
            stack.push(token)

        elif token == ')':
            top_token = stack.pop()

            while top_token != '(':
                postfix_list.append(top_token)
                top_token = stack.pop()

        else:
            while not stack.isEmpty() and OPERATORS_PRECEDENCE[
                    stack.peek()] >= OPERATORS_PRECEDENCE[token]:
                postfix_list.append(stack.pop())

            stack.push(token)

    while not stack.isEmpty():
        postfix_list.append(stack.pop())

    return postfix_list
Example #2
0
def infixToPostfix(infixexpr):
    prec = {
        '*': 3,
        '/': 3,
        '+': 2,
        '-': 2,
        '(': 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)
def iftopf(expression, order):
    #Infix to postfix conversion

    s = Stack()
    pf = []
    query_terms = expression.split(' ')
    for term in query_terms:
        if term not in (["OR", "AND", "NOT", "(", ")"]):
            term = stemmer.stem(term, 0, len(term) - 1)
            id1 = get_id(term)
            pf.append(id1)

        elif term == '(':
            s.push(term)
        elif term == ')':
            topterm = s.pop()
            while topterm != '(':
                pf.append(topterm)
                topterm = s.pop()
        else:
            if (not s.isEmpty() and s.peek() == "NOT"):
                pf.append(s.pop())

            while (not s.isEmpty()) and (order[s.peek()] >= order[term]
                                         and term != "NOT"):
                pf.append(s.pop())
            s.push(term)

    while not s.isEmpty():
        pf.append(s.pop())

    return pf
def match_check(node_list):
    # 遍历剔除*节点
    n_list = []
    for n in node_list:
        n_format = n.widget.replace(" ", "").replace("\n", "")
        if n_format[0] != "*":
            n_list.append(n_format)
    # 定义栈,+进
    s = Stack()
    flag = True  # 标记
    for n in n_list:
        # +节点进栈
        if n[0] == "+":
            s.push(n)
        else:
            # 没有+节点,第一个就是-,直接错误
            if s.isEmpty():
                flag = False
            else:
                # 获取栈顶+节点
                top = s.pop()
                # 如果和-节点匹配则正确,否则错误
                if n[1:] == top[1:]:
                    flag = True
                else:
                    return False
    if flag and s.isEmpty():
        return True
    else:
        return False
class MyQueue:
    def __init__(self):
        """
        Initialize your data structure here.
        """
        # 初始化
        self.stack1 = Stack()
        self.stack2 = Stack()

    def push(self, x):
        """
        Push element x to the back of queue.
        :type x: int
        :rtype: void
        """
        self.stack1.items.append(x)

    def pop(self):
        """
        Removes the element from in front of queue and returns that element.
        :rtype: int
        """
        if self.stack2.isEmpty() != True:  #判断栈2是否为空
            return self.stack2.items.pop()
        else:
            if self.stack1.isEmpty() != True:
                while self.stack1.size() != 1:
                    self.stack2.items.append(self.stack1.items.pop())
                return self.stack1.items.pop()
            else:
                if self.stack2.isEmpty() != True:
                    return self.stack2.items.pop()

    def peek(self):
        """
        Get the front element.
        :rtype: int
        """
        if self.stack2.isEmpty() != True:
            if len(self.stack2.items) >= 1:
                return self.stack2.items[len(self.stack2.items) - 1]
        else:
            if self.stack1.isEmpty() != True:
                return self.stack1.items[0]
            else:
                return False

    def empty(self):
        """
        Returns whether the queue is empty.
        :rtype: bool
        """
        return self.stack1.items == [] and self.stack2.items == []

    def size(self):
        return len(self.stack1.items) + len(self.stack2.items)
Example #6
0
def rev_string_s(my_str):
    rev_str_stack = Stack()
    for character in my_str:
        rev_str_stack.push(character)

    rev_str = []
    while not rev_str_stack.isEmpty():
        rev_str.append(rev_str_stack.pop())

    return ''.join(rev_str)
Example #7
0
def parChecker(symbolString):
    s = Stack()
    balanced = True
    index = 0
    while index < len(symbolString) and balanced:
        symbol = symbolString[index]
        if symbol == "(":
            s.push(symbol)
        else:
            if s.isEmpty():
                balanced = False
            else:
                s.pop()

        index = index + 1

    if balanced and s.isEmpty():
        return True
    else:
        return False
def divideby2(decnumber):
    remstack = Stack()
    while decnumber > 0:
        rem = decnumber % 2
        remstack.push(rem)
        decnumber = decnumber // 2
    binstring = ""
    while not remstack.isEmpty():
        binstring = binstring + str(remstack.pop())

    return binstring
def par_check(astring):
    s=Stack()
    balanced=True
    index=0
    while index<len(astring) and balanced:
        symbol=astring[index]
        if symbol=="(":
            s.push(symbol)
        else:
            if s.isEmpty():
                balanced=False
            else:
                top=s.pop()
                if not matches(top,symbol):
                    balanced=False
            index+=1
    if balanced and s.isEmpty():
        return True
    else:
        return False
Example #10
0
def check_palindromes(litral: str) -> None:
    stack = Stack()
    for s in litral:
        if s != ' ':
            stack.push(s)
    litral = ''
    reverse = ''
    while not stack.isEmpty():
        last = stack.pop()
        litral = last + litral
        reverse += last
    return reverse == litral
Example #11
0
def checkBalance(string):
    s = Stack()
    for c in string:
        if c in b:
            if b.index(c) < 3:
                s.push(c)
            else:
                if s.isEmpty():
                    return False
                else:
                    if s.pop() != b[b.index(c) - 3]:
                        return False
    return True
Example #12
0
def toPostfix(infixString):
    s = Stack()
    output = []
    infixString = infixString.split()

    for i in infixString:
        if i.isalnum():
            output.append(i)
        elif i == '(':
           s.push(i)
        elif i == ')':
            top = s.pop()
            while top != '(':
                output.append(top)
                top = s.pop()
        else:
            while (not s.isEmpty()) and (prec[s.peek()] > prec[i]):
                output.append(s.pop())
            s.push(i)
    
    while not s.isEmpty():
        output.append(s.pop())
    return " ".join(output)
Example #13
0
def baseConverter(decNumber, base):
    digits = "0123456789ABCDEF"

    if base not in [2, 8, 16]:
        raise ValueError(
            "The base has to be either binary(base 2), octal(base 8), or hexadecimal(base 16)."
        )

    remstack = Stack()

    while decNumber > 0:
        rem = decNumber % base
        remstack.push(rem)
        decNumber = decNumber // base

    newString = ""
    while not remstack.isEmpty():
        newString = newString + digits[remstack.pop()]

    return newString
 def export_tree(self, filename):
     f = open(filename, 'w')
     f.write('digraph Tree { \n node [shape=box] ;\n')
     st = Stack()
     st.push(self.root)
     while not st.isEmpty():
         node = st.pop()
         name, label = node.name, node.label
         if node.leaf:
             content = '[label="{}",name="{}"];\n'.format(label, name)
             f.write(name+content)
             continue
         else:
             content = '[name="{}",basis="{}"];\n'.format(name,node.basis)
             f.write(name+content)
             for x in node.child:
                 child_node = node.child[x]
                 st.push(child_node)#保证栈内总是Node类型
                 f.write('{} -> {} ;\n'.format(name, child_node.name))
             continue
     f.write('}')
     f.close()