Example #1
0
def postixcalculator(expression, mydict):
    operators, temp = "-/+*", ""
    user_input = expression.split(" ")
    stack = ArrayStack()

    for elem in user_input:
        if elem in operators:
            right = stack.pop()
            left = stack.pop()
            if elem == "+":
                stack.push(left + right)
            elif elem == "-":
                stack.push(left - right)
            elif elem == "*":
                stack.push(left * right)
            else:  # elem == "/"
                if right == 0:
                    raise Exception("Divide by Zero Error")
                stack.push(left / right)
        elif elem in mydict:
            stack.push(mydict[elem])
        elif elem.isdigit():
            stack.push(int(elem))
        elif elem.isalpha():
            stack.push(elem)
            temp += elem

    if temp == "":
        val = stack.top()
        print(val)
    else:
        mydict[temp] = stack.top()
        print(temp)
        return (stack.top())
Example #2
0
class MaxStack:
    def __init__(self):
        self.data = ArrayStack()

    def __len__(self):
        return len(self.data)

    def is_empty(self):
        return len(self.data) == 0

    def top(self):
        if (self.data.is_empty()):
            raise Exception("Stack is empty")
        return self.data.top()[0]

    def push(self, val):
        if self.data.is_empty():
            self.data.push((val, val))
        elif self.data.top()[1] > val:
            self.data.push((val, self.data.top()[1]))
        else:
            self.data.push((val, val))

    def pop(self):
        if self.data.is_empty():
            raise Exception("Stack is empty")
        return self.data.pop()[0]

    def max(self):
        if self.data.is_empty():
            raise Exception("Stack is empty")
        return self.data.top()[1]
class Queue:
    def __init__(self):
        self.stack = ArrayStack()
        self.helper = ArrayStack()

    def __len__(self):
        return len(self.stack)

    def is_empty(self):
        return len(self) == 0

    def enqueue(self,elem):
        self.stack.push(elem)

    def first(self):
        if self.is_empty():
            raise Exception("The Queue is empty")
        for i in range(len(self)):
            self.helper.push(self.stack.pop())
        val = self.helper.top()
        for i in range(len(self)):
            self.stack.push(self.helper.pop())
        return val

    def dequeue(self):
        if self.is_empty():
            raise Exception("The Queue is empty")
        for i in range(len(self)):
            self.helper.push(self.stack.pop())
        val = self.helper.pop()
        for i in range(len(self.helper)):
            self.stack.push(self.helper.pop())
        return val
class MidStack:

    def __init__(self):
        self.data = ArrayStack()
        self.reorder = ArrayDeque()

    def __len__(self):
        return len(self.data.data)

    def is_empty(self):
        return len(self) == 0
    
    def push(self,e):
        self.data.push(e)

    def top(self):
        return self.data.top()
        
    def pop(self):
        return self.data.pop()
        
    def mid_push(self,e):
        if len(self)%2==0:
            for i in range((len(self)//2), len(self)):
                self.reorder.enqueue_first((self.pop()))
        else:
            for i in range(((len(self)//2)+1), len(self)):
                self.reorder.enqueue_first((self.pop()))
        self.push(e)
        for i in range(len(self.reorder)):
            self.push(self.reorder.dequeue_first())
Example #5
0
def postfix_calc():
    exp = input('-->')
    dct = {}
    s = ArrayStack()
    while exp != 'done()':
        exp = input('-->')

        if '=' not in exp:
            for char in exp:
                if char.isdigit() == True:
                    s.push(char)

                elif char in '*-/+':
                    operand1 = int(s.pop())
                    operand2 = int(s.pop())

                    if char == '+':
                        s.push(operand1 + operand2)
                    elif char == '-':
                        s.push(operand1 + operand2)
                    elif char == '*':
                        s.push(operand1 * operand2)
                    elif char == '/':
                        s.push(operand1 * operand2)
            print(s.top())

        else:
            for char in exp:
                if char.isalpha() == True:
                    dct[char] = stack.top()

            print(char)
Example #6
0
class Queue:
    def __init__(self):
        self.enq = ArrayStack()
        self.deq = ArrayStack()

    def __len__(self):
        return len(self.deq)

    def is_empty(self):
        return len(self.deq) == 0

    def first(self):
        if self.deq.is_empty():
            raise Exception("Queue is Empty")
        else:
            return self.deq.top()

    def enqueue(self, val):
        if self.deq.is_empty():
            self.deq.push(val)
        else:
            for q in range(len(self.deq)):
                self.enq.push(self.deq.pop())
            self.enq.push(val)
            for q in range(len(self.enq)):
                self.deq.push(self.enq.pop())

    def dequeue(self):
        if self.deq.is_empty():
            raise Exception("Queue is Empty")
        else:
            return self.deq.pop()
Example #7
0
def test_ArrayStack():
    s = ArrayStack()
    print(s.empty())
    for i in range(33):
        s.push(i)
        print('loop', i)
    print(s.top())
    s.print()
Example #8
0
def sortStack(s):
    r = ArrayStack()

    while not s.is_empty:
        tmp = s.pop()
        while not r.is_empty and tmp < r.top():
            s.push(r.pop())
        r.push(tmp)  # 当r是空的 或者 tmp比r最上面的大,可以直接push进去
    return r
def evalExp(expr):
    valStk = ArrayStack()
    opStk = ListStack()
    for z in expr:
        if z.isdigit():
            valStk.push(z)
        elif z in "+-*/":
            repeatOps(z, valStk, opStk)
            opStk.push(z)
    repeatOps('$', valStk, opStk)
    return valStk.top()
Example #10
0
class TestArrayStack(unittest.TestCase):

    def setUp(self):
        self.s = ArrayStack()
        self.s.push(1)
        self.s.push(2)

    def test_instantiation(self):
        print('Can create an instance')
        self.assertIsInstance(self.s, ArrayStack)

    def test_is_empty_method(self):
        print('Can check if the stack is empty')
        self.s.pop()
        self.s.pop()
        self.assertEqual(self.s.is_empty(), True)

    def test_push_method(self):
        print('Can add element to the top of the stack')
        self.s.push(5)

        self.assertEqual(self.s.top(), 5)

    def test_pop_method(self):
        print('Can remove element(s) from the top of the stack')

        self.assertEqual(self.s.pop(), 2)
        self.assertEqual(self.s.top(), 1)

    def test_length_checking(self):
        print('Can check the length of the stack')
        self.assertEqual(len(self.s), 2)

    def test_exception_raising(self):
        print('Can raise exception while performing action(s) on empty stack')
        self.s.pop()
        self.s.pop()

        with self.assertRaises(Empty):
            self.s.top()
            self.s.pop()
Example #11
0
class MaxStack:
    def __init__(self):
        self.data = ArrayStack()
        self.curr_max = None

    def __len__(self):
        return len(self.data)

    def is_empty(self):
        return len(self) == 0

    def push(self, e):
        # check who is the current max at the time
        if (self.is_empty()):
            self.data.push(tuple(
                (e, e)))  # val, currmax (its won max bc nothing else)
            self.curr_max = e
        else:
            if (e > self.curr_max):
                self.curr_max = e
            self.data.push(tuple((e, self.curr_max)))

    def top(self):
        if (self.is_empty()):
            raise Exception("Stack is empty")
        return self.data.top()[0]

    def pop(self):
        if (self.is_empty()):
            raise Exception("Stack is empty")
        popped_val = self.top()
        self.data.pop()
        self.curr_max = self.data.top()[1]  # next max to max down
        return popped_val

    def max(self):
        if (self.is_empty()):
            raise Exception("Stack is empty")
        return self.curr_max
Example #12
0
class MaxStack:
    def __init__(self):
        self.stack = ArrayStack()
        self._max = None

    def __len__(self):
        return len(self.stack)

    def is_empty(self):
        return len(self) == 0

    def push(self,elem):
        if self.is_empty():
            self._max = elem
        elif elem > self._max:
            self._max = elem
        self.stack.push((elem,self._max))

    def top(self):
        if self.is_empty():
            raise Exception("The max_s is empty")
        return self.stack.top()[0]

    def pop(self):
        if self.is_empty():
            raise Exception("The max_s is empty")
        elem = self.stack.pop()[0]
        if not self.is_empty():
            self._max = self.stack.top()[1]
        else:
            self._max = None
        return elem

    def max(self):
        if self.is_empty():
            raise Exception("The max_s is empty")        
        return self._max
def main():
    S = ArrayStack()
    print(len(S))
    S.push(5)
    S.push(3)
    print(len(S))
    print(S.pop())
    print(S.is_empty())
    print(S.pop())
    print(S.is_empty())
    S.push(7)
    S.push(9)
    print(S.top())
    S.push(4)
    print(len(S))
    print(S.pop())
    S.push(6)
Example #14
0
class MidStack:
    def __init__(self):
        self.stac = ArrayStack()
        self.dque = ArrayDeque()

    def __len__(self):
        return len(self.stac) + len(self.dque)

    def is_empty(self):
        return len(self.stac) == 0 and len(self.dque) == 0

    def top(self):
        if (self.is_empty()):
            raise Exception("Stack is empty")
        return self.dque.last()

    def push(self, val):
        if self.is_empty():
            self.stac.push(val)
        elif len(self) % 2 == 0:
            self.stac.push(self.dque.first())
            self.dque.dequeue_first()
            self.dque.enqueue_last(val)
        elif len(self) % 2 == 1:
            self.dque.enqueue_last(val)

    def pop(self):
        if self.is_empty():
            raise Exception("Stack is empty")
        else:
            if len(self.stac) == 1 and len(self.dque) == 0:
                return self.stac.pop()
            elif len(self) % 2 == 0:
                return self.dque.dequeue_last()
            elif len(self) % 2 == 1:
                self.dque.enqueue_first(self.stac.top())
                self.stac.pop()
                return self.dque.dequeue_last()

    def mid_push(self, val):
        if len(self) % 2 == 0:
            self.stac.push(val)
        else:
            self.dque.enqueue_first(val)
Example #15
0
def evalExp(expr):
    # on utilise une pile pour les valeurs et une pile pour les opérations
    valStk = ArrayStack()
    opStk = ListStack()

    # tant qu'il y a des jetons en entrée
    for z in expr:
        if z.isdigit():  # si chiffre, on l'empile
            valStk.push(z)
            if trace:
                print("chiffre dans la pile", valStk)
        elif z in "+-*/":  # si opération, on voit si on peut l'effectuer
            if trace:
                print("opération lue : ", z)
            repeatOps(z, valStk, opStk)
            # on empile l'opération
            opStk.push(z)
            if trace:
                print("opération dans la pile", opStk)
    # on exécute l'opération sur la pile, le cas échéant
    repeatOps('$', valStk, opStk)
    # le resultat se trouve sur le top de la pile des valeurs
    return valStk.top()