def __init__(self):
     """
     Initialize your data structure here.
     """
     # 初始化
     self.stack1 = Stack()
     self.stack2 = Stack()
Beispiel #2
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
Beispiel #3
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'))
Beispiel #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
Beispiel #5
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()
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 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()
Beispiel #8
0
class QueueS:
    s1 = Stack()
    s2 = Stack()

    def __init__(self):
        print('Stack Q initiated')

    def nQ(self, x):
        self.s1.push(x)

    def dQ(self):
        while not self.s1.isEmpty():
            self.s2.push(self.s1.pop())

        toReturn = self.s2.pop()

        while not self.s2.isEmpty():
            self.s1.push(self.s2.pop())

        return toReturn
 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])
Beispiel #10
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 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))
Beispiel #12
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)
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)
Beispiel #14
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)
Beispiel #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
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
Beispiel #17
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
Beispiel #18
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
Beispiel #19
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
 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()
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
Beispiel #22
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
Beispiel #23
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2020/7/13 10:33 AM
# @Author  : Charles He
# @File    : recursion_stack.py
# @Software: PyCharm

from pythonds import Stack

rStack = Stack()


def toStr(n, base):
    convertStr = '0123456789ABCDEF'

    if n < base:
        rStack.push(convertStr[n])
    else:
        rStack.push(convertStr[n % base])
        toStr(n // base, base)
#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())
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()
 def __init__(self):
     self.inbox = Stack()
     self.outbox = Stack()
Beispiel #27
0
import matplotlib.pyplot as plt
from pythonds import Stack
from queue_with_linked_list_in import Queue

t1 = timeit.Timer('some_collection.push(1)',
                  'from __main__ import some_collection')
t2 = timeit.Timer('some_collection.enqueue(1)',
                  'from __main__ import some_collection')
# 记录数据的列表
lengths = []  # 横轴 collection长度
times1 = []  # 竖轴数据1:stack方法所用时间
times2 = []  # 竖轴数据2:queue方法所用时间
# 长度切换
for length in range(10000, 1000001, 20000):
    lengths.append(length)
    # some_collection的长度填充
    some_collection = Stack()
    some_collection.items = list(range(length))
    # 测试开始
    times1.append(t1.timeit(10))
    # queue测试
    some_collection = Queue()
    for i in range(length):
        some_collection.enqueue(i)
    times2.append(t2.timeit(10))
# 绘图
plt.plot(lengths, times1, 'o', label='linked_list')
plt.plot(lengths, times2, 'o', label='common_list')
plt.legend()
plt.show()
Beispiel #28
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()
Beispiel #29
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)