Esempio n. 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
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
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
Esempio n. 4
0
def buildParseTree(fpexp):
    '''
    1.If the current token is a '(', add a new node as the left child of
      the current node, and descend to the left child.
    2.If the current token is in the list ['+','-','/','*'], set the root
      value of the current node to the operator represented by the current
      token. Add a new node as the right child of the current node and
      descend to the right child.
    3.If the current token is a number, set the root value of the current
      node to the number and return to the parent.
    4.If the current token is a ')', go to the parent of the current node.
    '''
    fplist = fpexp.split()
    pStack = Stack()
    eTree = BinaryTree('')
    currentTree = eTree
    for i in fplist:
        if i == '(':
            currentTree.insertLeft('')
            pStack.push(currentTree)
            currentTree = currentTree.getLeftChild()
        elif i not in ['+', '-', '*', '/', ')']:
            currentTree.setRootValue(int(i))
            parent = pStack.pop()
            currentTree = parent
        elif i in ['+', '-', '*', '/']:
            currentTree.setRootValue(i)
            currentTree.insertRight('')
            pStack.push(currentTree)
            currentTree = currentTree.getRightChild()
        elif i == ')':
            currentTree = pStack.pop()
        else:
            raise ValueError
    return eTree
Esempio n. 5
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)
Esempio n. 6
0
def hanoi(n: int, from_stack: Stack, assist_stack: Stack, to_stack: Stack):
    if n == 1:
        to_stack.push(from_stack.pop())
        print(from_stack, '==>', to_stack)
    else:
        hanoi(n - 1, from_stack, to_stack, assist_stack)
        to_stack.push(from_stack.pop())
        print(from_stack, '==>', to_stack)
        hanoi(n - 1, assist_stack, from_stack, to_stack)
Esempio n. 7
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)
 def clarrify(self, data):
     st = Stack()
     st.push(self.root)
     while st is not None:
         node = st.pop()
         if node.leaf:
             return data.label == node.label
         basis = node.basis
         feature = data.data[basis]
         st.push(node.child[feature])
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
Esempio n. 10
0
def isPalindrome1s(s):
    stack = Stack()
    for letter in s:
        stack.push(letter)
    for i in s:
        if i != stack.pop():
            return False
    return True


# print(isPalindrome1s('madsssddam'))
# print(isPalindrome1s('madsssdam'))
Esempio n. 11
0
def evaluate_postfix(postfix):
    # If operand, push into the stack
    # If operator, pop two operands, push the result into the stack
    # Pop result from stack
    stack = Stack()
    for i in postfix:
        if i.isalnum():
            stack.push(i)
        else:
            op2, op1 = str(stack.pop()), str(stack.pop())
            stack.push(eval(op1 + i + op2))
    return stack.pop()
Esempio n. 12
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
Esempio n. 13
0
def evaluate(postfixString):
    s = Stack()
    postfixString = postfixString.split()

    for i in postfixString:
        if i.isnumeric():
            s.push(int(i))
        else:
            op2 = s.pop()
            op1 = s.pop()
            result = calculate(op1, op2, i)
            s.push(result)
    return s.pop()
Esempio n. 14
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
Esempio n. 15
0
def huffman_decoding(data, tree):
    x = 0
    root = tree.root
    decoder_stack = Stack()
    decoded_word = ""
    while x < len(data):
        if data[x] == "0":
            decoder_stack.push(root)
            root = root.left
        elif data[x] == "1":
            decoder_stack.push(root)
            root = root.right
        if root.data != 0:
            decoded_word += root.data
            while decoder_stack.size() != 0:
                root = decoder_stack.pop()
        x += 1
    return decoded_word
Esempio n. 16
0
def rpn_calc():
    postfixExpr = input(
        "Please enter an expression in Reverse Polish notation: ")
    operandStack = Stack()
    tokenList = postfixExpr.split()

    for token in tokenList:
        if token in "0123456789":
            operandStack.push(int(token))
        else:
            operand2 = operandStack.pop()
            operand1 = operandStack.pop()
            result = doMath(token, operand1, operand2)
            operandStack.push(result)

    if operandStack.size() > 1:
        raise Exception("The expression is invalid.")

    return operandStack.pop()
def returnDoclist(pf, dic, order):
    """
    Computes the boolean query and return the list with document id
    """
    doc = [x for x in range(1, len(documents))]
    s = Stack()
    for query_term in pf:
        if (query_term not in order):
            if (query_term in dic):
                data = [x[0] for x in dic[query_term][1]]
            elif (query_term in stopWords):
                #stopword indication
                data = ['s']
            else:
                data = []
            s.push(data)
        else:
            if (query_term == "AND"):
                l1 = s.pop()
                l2 = s.pop()
                if ('s' in l1 and 's' in l2):
                    res = ['s']
                elif ('s' in l1):
                    res = l2
                elif ('s' in l2):
                    res = l1
                else:
                    res = set(l1).intersection(l2)
                s.push(res)
            elif (query_term == "OR"):
                l1 = s.pop()
                l2 = s.pop()
                if ('s' in l1 and 's' in l2):
                    res = ['s']
                elif ('s' in l2):
                    res = l1
                elif ('s' in l1):
                    res = l2
                else:
                    res = set(l1).union(l2)
                s.push(res)
            elif (query_term == "NOT"):
                l = s.pop()
                if ('s' in l):
                    res = []
                else:
                    res = set(doc) - set(l)
                s.push(res)
    result = s.pop()
    final = []
    if 's' not in result:
        final = result
    return final
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
Esempio n. 19
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
Esempio n. 20
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
Esempio n. 21
0
def buildParseTree(fpexp):
    fplist = fpexp.split()
    pStack = Stack()
    eTree = BinaryTree('')
    pStack.push(eTree)
    currentTree = eTree
    for i in fplist:
        if i == '(':
            currentTree.insertLeft('')
            pStack.push(currentTree)
            currentTree = currentTree.getLeftChild()
        elif i not in ['+', '-', '*', '/', ')']:
            currentTree.setRootVal(int(i))
            parent = pStack.pop()
            currentTree = parent
        elif i in ['+', '-', '*', '/']:
            currentTree.setRootVal(i)
            currentTree.insertRight('')
            pStack.push(currentTree)
            currentTree = currentTree.getRightChild()
        elif i == ')':
            currentTree = pStack.pop()
        else:
            raise ValueError
    return eTree
 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()
Esempio n. 23
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)
def eval_expr(expr):
    s = Stack()
    for token in expr.split():
        if token in ['+', '-', '*', '/', '//', '%', '**']:
            if s.size() < 2:
                raise IndexError("Empty Stack, too few operands.")
            else:
                op2 = s.pop()
                op1 = s.pop()
                result = do_math(op1, op2, token)
                s.push(result)
        elif token == '=':
            if s.size() > 1:
                raise IndexError("Stack is not empty, too many operands.")
            else:
                return s.pop()
        # Unknown operator was not on the assignment but I accounted for it.
        # E.g. '?' would be seen as an unknown operator in any expression.
        elif token not in ['+', '-', '*', '/', '//', '%', '**', '='
                           ] and not token.isdigit():
            raise ValueError("Invalid operator.")
        else:
            s.push(int(token))
class Queue:
    def __init__(self):
        self.inbox = Stack()
        self.outbox = Stack()

    def enqueue(self, item):
        while self.outbox.size() != 0:
            self.inbox.push(self.outbox.pop())
        self.inbox.push(item)

    def dequeue(self):
        while self.inbox.size() != 0:
            self.outbox.push(self.inbox.pop())
        return self.outbox.pop()
#ADT = Abstract Data types

#Stacks and operations

from pythonds import Stack

int_stack = Stack()
int_stack.push(1)
int_stack.push(2)
print(int_stack.pop(), end=",")
int_stack.push(3)
print(int_stack.pop(), end=",")
print(int_stack.pop())
Esempio n. 27
0
    # 设置长度
    if last_disk_size != None:
        length = last_disk_size[0] - 1
        if length <= 0:
            length = 1
            for i in self.items:
                i.resizemode('user')
                i.shapesize(i.shapesize()[0] + 1, 0.5)
        item.shapesize(*(length, last_disk_size[1]))
    # 海龟位置y坐标
    index = len(self.items) - 1
    item_y = 20 * 0.5 / 2 + index * 20 * 0.5 + self.y
    # 海龟就位
    self.items[index]: Disk.penup()
    self.items[index].goto(self.x, item_y)


Stack.push = push
Stack.__str__ = __str__

screen = turtle.Screen()

from_stack = Stack('From Stack', -300, -150)
for i in range(6):
    from_stack.push(Disk(0))
assist_satck = Stack('Assist Satck', 0, 100)
to_stack = Stack('To Stack', 300, -150)
hanoi(from_stack.size(), from_stack, assist_satck, to_stack)
screen.mainloop()
        to_stack.push(from_stack.pop())
        print(from_stack, '==>', to_stack)
    else:
        hanoi(n - 1, from_stack, to_stack, assist_stack)
        to_stack.push(from_stack.pop())
        print(from_stack, '==>', to_stack)
        hanoi(n - 1, assist_stack, from_stack, to_stack)


# 重新定义Stack方法,使其可以打印名字
def __init__(self, name: str):
    self.items = []
    self.name = name


Stack.__init__ = __init__


def __str__(self):
    return self.name


Stack.__str__ = __str__

from_stack = Stack('From Stack')
for i in range(64):
    from_stack.push('disk')
assist_satck = Stack('Assist Satck')
to_stack = Stack('To Stack')
hanoi(from_stack.size(), from_stack, assist_satck, to_stack)
Esempio n. 29
0
from pythonds import Stack

s = Stack()

for i in range(1000):
    s.push(i)
while s:

    k = s.pop()
    print(k)
    if k == 0:
        break

# which could also be done as:
s = StackFromSequence(range(1000))
while s:
    try:
        print s.pop()
    except:
        print "Stack EMPTY"
# or a little different
s = StackFromSequence(range(1000))
print s.as_tuple()
print s.as_list()