Example #1
0
class MyQueue:
    def __init__(self):
        self._stack = ArrayStack()
        self._inverted = False
        self._size = 0

    def peek(self):
        # stack = self._stack
        if self._stack.is_empty():
            raise Empty('Stack is empty')
        if not self._inverted:
            self.invert_stack()
        return self._stack.peek()

    def push(self, value):
        if self._inverted:
            self.invert_stack()
        self._stack.push(value)

    def pop(self):
        if self._stack.is_empty():
            raise Empty('Empty stack')
        if not self._inverted:
            self.invert_stack()
        return self._stack.pop()

    def invert_stack(self):
        temp = ArrayStack()
        self._inverted = not self._inverted

        while self._stack.peek() is not None:
            temp.push(self._stack.pop())
        self._stack = temp
Example #2
0
def test_three_stack():
    R = ArrayStack()
    R.push(1)
    R.push(2)
    R.push(3)

    S = ArrayStack()
    S.push(4)
    S.push(5)

    T = ArrayStack()
    T.push(6)
    T.push(7)
    T.push(8)
    T.push(9)

    three_stack(R, S, T)

    # check result
    print("Stack R")
    for _ in range(len(R)):
        print(R.pop())
    print("Stack S")
    for _ in range(len(S)):
        print(S.pop())
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())
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 StackQueue():
    """Implement ADT queue using two stacks"""
    def __init__(self):
        self._s = ArrayStack()
        self._t = ArrayStack()

    def __len__(self):
        return len(self._s) + len(self._t)

    def is_empty(self):
        return self._s.is_empty() and self._t.is_empty()

    def enqueue(self, value):
        self._s.push(value)

    def dequeue(self):
        if not self._t.is_empty():
            return self._t.pop()
        else:
            if self._s.is_empty():
                raise ValueError("Empty Queue")
            else:
                while not self._s.is_empty():
                    self._t.push(self._s.pop())
                return self._t.pop()
Example #6
0
 def reverse_list(self, l):
     st = ArrayStack()
     for k in range(len(l)):
         st.push(l[k])
     for j in range(len(l)):
         l[j] = st.pop()
     return l
Example #7
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 #8
0
    def invert_stack(self):
        temp = ArrayStack()
        self._inverted = not self._inverted

        while self._stack.peek() is not None:
            temp.push(self._stack.pop())
        self._stack = temp
Example #9
0
def is_matched_html(raw):
    S = ArrayStack()
    j = raw.find('<')
    while j != -1:
        k = raw.find('>', j + 1)
        if k == -1:
            return False
        tag = raw[j + 1:k]
        many = tag.split(" ")
        if len(many) > 1:
            if not check_atributes(many[1:]):
                return False
            tag = many[0]

        if not tag.startswith('/'):
            # its opening tag
            S.push(tag)
        else:
            # its ending tag
            if S.is_empty():
                return False
            if tag[1:] != S.pop():
                return False
        j = raw.find('<', k + 1)
    return S.is_empty()
Example #10
0
def reverse_list(arr):
    S = ArrayStack()
    for item in arr:
        S.push(item)
    for i in range(len(arr)):
        arr[i] = S.pop()
    return arr
Example #11
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 #12
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
Example #13
0
def reverse_file(filename):
    S = ArrayStack()
    original = open(os.path.join(__location__, filename))
    for line in original:
        S.push(line.rstrip('\n'))
    original.close()
    output = open(os.path.join(__location__, 'output.txt'), 'w')
    while not S.is_empty():
        output.write(S.pop() + '\n')
    output.close()
def reverse_file(filename):
    S = ArrayStack()
    original = open(filename)
    for line in original:
        S.push(line.rstrip('\n'))
    original.close()
    output = open(filename, 'w')
    while len(S):
        output.write(S.pop() + '\n')
    output.close()
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 #16
0
    def reverse_file(self, filename):
        S = ArrayStack()
        original = open(filename)
        for line in original:
            S.push(line)
        original.close()

        out = open(filename, 'w')
        while not S.is_empty():
            out.write(S.pop() + '\n')
        out.close()
Example #17
0
		def ChildParentOperatorTest(self, postfixExpression):
			stack = ArrayStack()
			for x in range(0, len(postfixExpression)):
				if postfixExpression[x] not in operator:
					stack.push(postfixExpression[x])
				else:
					op2 = stack.pop()
					op1 = stack.pop()
					if op1[-1] == postfixExpression[x] or op2[-1] == postfixExpression[x]:
						return False
					stack.push(op1 + op2 + postfixExpression[x])
			return True
Example #18
0
def reverse_file(filename):
    """ Overwrites given file with its content line-by-line reversed """
    s = ArrayStack()
    original = open(filename)
    for line in original:
        s.push(line.rstrip('\n'))
    original.close()

    new_filename = 'new_{}.txt'.format(randrange(0, 100, 2))
    output = open(new_filename, 'w')
    while not s.isEmpty():
        output.write(s.pop() + '\n')
    output.close()
def check(expression):
    stack = ArrayStack()

    for delimeter in expression:
        if delimeter in left:
            stack.push(delimeter)  # add delemeter to stack
        elif delimeter in right:
            if stack.is_empty():
                return False
            if left.index(stack.pop()) != right.index(delimeter):
                return False

    return stack.is_empty()  # return true if all delimeters are matched
Example #20
0
 def is_matched(expr):
     lefty = '({['
     righty = ')}]'
     s = ArrayStack()
     for c in expr:
         if c in  lefty:
             s.push(c)
         elif c in righty:
             if s.is_empty():
                 return False
             if righty.index(c) != lefty.index(s.pop()):
                 return False
     return s.is_empty()
Example #21
0
 def PostfixToPrefix(self, postfixExpression):
     stack = ArrayStack()
     stringPrefix = ""
     for x in range(0, len(postfixExpression)):
         if (postfixExpression[x] in operator):
             second = stack.pop()
             one = stack.pop()
             stack.push(postfixExpression[x] + one + second)
         else:
             stack.push(postfixExpression[x])
     while (not stack.is_empty()):
         stringPrefix += stack.pop()
     return stringPrefix
Example #22
0
		def PostfixToPrefix(self, postfixExpression):
			stack = ArrayStack()
			stringPrefix = ""
			for x in range(0, len(postfixExpression)):
				if (postfixExpression[x] in operator):
					second = stack.pop()
					one = stack.pop()
					stack.push(postfixExpression[x]+one+second)
				else:
					stack.push(postfixExpression[x])
			while (not stack.is_empty()):
						stringPrefix += stack.pop()
			return stringPrefix
Example #23
0
		def PostfixToInfix(self, postfixExpression):
			stack = ArrayStack()
			stringInfix = ""
			for x in range (0, len(postfixExpression)):
				if postfixExpression[x] not in operator:
					stack.push(postfixExpression[x])
				else:
					op1 = stack.pop()
					op2 = stack.pop()
					stack.push(op1 + postfixExpression[x] + op2)
			while not stack.is_empty():
				stringInfix += stack.pop()
			return stringInfix
Example #24
0
 def ChildParentOperatorTest(self, postfixExpression):
     stack = ArrayStack()
     for x in range(0, len(postfixExpression)):
         if postfixExpression[x] not in operator:
             stack.push(postfixExpression[x])
         else:
             op2 = stack.pop()
             op1 = stack.pop()
             if op1[-1] == postfixExpression[x] or op2[
                     -1] == postfixExpression[x]:
                 return False
             stack.push(op1 + op2 + postfixExpression[x])
     return True
Example #25
0
 def PostfixToInfix(self, postfixExpression):
     stack = ArrayStack()
     stringInfix = ""
     for x in range(0, len(postfixExpression)):
         if postfixExpression[x] not in operator:
             stack.push(postfixExpression[x])
         else:
             op1 = stack.pop()
             op2 = stack.pop()
             stack.push(op1 + postfixExpression[x] + op2)
     while not stack.is_empty():
         stringInfix += stack.pop()
     return stringInfix
Example #26
0
def is_match(expr):
    lefty = '({['
    righty = ')}]'
    S = ArrayStack()
    for c in expr:
        if c in lefty:
            S.push(c)
        elif c in righty:
            if S.is_empty():
                return False
            if righty.index(c) != lefty.index(S.pop()):
                return False
    return "Valid" if S.is_empty() else "Invalid"
Example #27
0
def is_matched(expr):
    """ Returns true if the arithmatic express is true, false otherwise """
    left = '({['
    right = ')}]'
    s = ArrayStack()
    for c in expr:
        if c in left:
            s.push(c)
        elif c in right:
            if s.is_empty():
                return False
            if right.index(c) != left.index(s.pop()):
                return False
    return s.is_empty()
Example #28
0
def flatten_dll(dll):
    result = DoublyLinkedList()
    temp = ArrayStack()
    for elem in dll:
        temp.push(elem)

    while not temp.is_empty():
        elem = temp.pop()
        if isinstance(elem, DoublyLinkedList):
            for sub_elem in elem:
                temp.push(sub_elem)
        else:
            result.add_first(elem)
    return result
Example #29
0
		def PrefixToPostfix(self, prefixExpression):
			stack = ArrayStack()
			stringPostfix = ""
			prefixExpression = prefixExpression[::-1]
			for x in range(0, len(prefixExpression)):
				if (prefixExpression[x] in operator):
					one = stack.pop()
					second = stack.pop()
					stack.push(one+second+prefixExpression[x])
				else:
					stack.push(prefixExpression[x])
			while (not stack.is_empty()):
						stringPostfix += stack.pop()   
			return stringPostfix
Example #30
0
 def PrefixToPostfix(self, prefixExpression):
     stack = ArrayStack()
     stringPostfix = ""
     prefixExpression = prefixExpression[::-1]
     for x in range(0, len(prefixExpression)):
         if (prefixExpression[x] in operator):
             one = stack.pop()
             second = stack.pop()
             stack.push(one + second + prefixExpression[x])
         else:
             stack.push(prefixExpression[x])
     while (not stack.is_empty()):
         stringPostfix += stack.pop()
     return stringPostfix
Example #31
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 #32
0
def is_matched(s):
    left = '([{'
    right = ')]}'
    stack = ArrayStack()

    for c in s:
        if c in left:
            stack.push(c)
        elif c in right:
            if stack.is_empty():
                return False
            elif left.index(stack.pop()) != right.index(c):
                return False

    return stack.is_empty()
Example #33
0
 def dfs(self, r: int):
     seen = np.zeros(self.n, np.bool_)
     l = []
     s = ArrayStack()
     s.push(r)
     while s.size() > 0:
         i = s.pop()
         l.append(i)
         seen[i] = True
         ngh = self.out_edges2(i)
         for j in range(0, ngh.size()):
             if seen[ngh.get(j)] == False:
                 s.push(ngh.get(j))
             else:
                 continue
     return l
def parentheses_match(expr):
    """ Return True if all delimiters are properly match; False otherwise."""
    left = '({['        # opening delimiters
    right = ')}]'           # respective closing delims
    
    S = ArrayStack() 
    for c in expr:
        if c in left:
            S.push(c)                # push left delimiter on stack
        elif c in right:
            if S.is_empty():    # nothing to match with
                return False
            if right.index(c) != left.index(S.pop()):
                return False            # mismatched
    return S.is_empty()            # were all symbols matched?
                
class Queue:
    def __init__(self):
        self._in = ArrayStack()
        self._out = ArrayStack()

    def enqueue(self, e):
        self._in.push(e)

    def dequeue(self):
        if self._out.is_empty():
            while not self._in.is_empty():
                self._out.push(self._in.pop())

        if self._out.is_empty():
            raise Empty()
        return self._out.pop()
Example #36
0
    def InfixToPostfix(self, infixExpression):
        stackyStack = ArrayStack()
        stringPostfix = ""

        for character in infixExpression:
            if (character not in operator):
                stringPostfix += character
            elif stackyStack.is_empty():
                stackyStack.push(character)
            else:
                stringPostfix += stackyStack.pop()
                stackyStack.push(character)

        while (not stackyStack.is_empty()):
            stringPostfix += stackyStack.pop()

        return stringPostfix
def check_binaryString(input_string):
  stack = ArrayStack()
  if len(input_string)%2 != 0:
    return False

  for i in input_string:
    if i == "1":
      stack.push(i)

  for i in input_string:
    if i == "0":
      try:
        stack.pop()
      except:
        return False

  return stack._size == 0
Example #38
0
 def is_matched(self, expr):
     """
     Running time : O(n)
     :return: true if there are matching opening/closing symbols
     """
     lefty = '({['
     righty = ')}]'
     S = ArrayStack()
     for c in expr:
         if c in lefty:
             S.push(c)
         elif c in righty:
             if S.is_empty():
                 return False
             if righty.index(c) != lefty.index(S.pop()):
                 return False
     return S.is_empty()
Example #39
0
		def InfixToPostfix(self, infixExpression):
				stackyStack = ArrayStack()
				stringPostfix = ""
				
				for character in infixExpression:
						if (character not in operator):
								stringPostfix += character
						elif stackyStack.is_empty():
								stackyStack.push(character)
						else:
								stringPostfix += stackyStack.pop()
								stackyStack.push(character)
								
								
				while (not stackyStack.is_empty()):
						stringPostfix += stackyStack.pop()              
						
				return stringPostfix
Example #40
0
 def is_matched_html(self, raw):
     """
     :return: True if there are correct opening and closing html tags
     """
     s = ArrayStack()
     j = raw.find('<')
     while j != -1:
         k = raw.find('>', j+1)
         if k == -1:
             return False
         tag = raw[j+1:k]                # strip < >
         if not tag.startswith('/'):     # opening tag
             s.push(tag)
         else:
             if s.is_empty():
                 return False
             if tag[1:] != s.pop():
                 return False
         j = raw.find('<', k+1)
     return s.is_empty()
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 #42
0
		def AreaComputation(self, postfixExpression):
			stacky = ArrayStack()
			BestCandidate = 0
			RealDict = {}
			RealNote = ""
			for y in range(0, 2**len(self._rectangles)):
				rectCounter = 0
				flipDict = {}
				FlipNote = "{0:b}".format(y)
				FlipNote = "0"* (len(self._rectangles)-len(FlipNote)) + FlipNote
				for x in range(0, len(postfixExpression)):
					currentChar = postfixExpression[x]
					if (currentChar not in operator):
						rect = self._dictionnary[currentChar]
						flipDict[currentChar] = "0"
						if (FlipNote[rectCounter] == "1"):
							#print(rectCounter)
							#print(FlipNote)
							#print("Is flipping " + currentChar)
							flipDict[currentChar] = "1"
							rect = rect[::-1] 
						stacky.push(rect)
						rectCounter += 1
					else:
						Rightchild = stacky.pop()
						Leftchild = stacky.pop()
						rightWidth, rightHeight = Rightchild
						leftWidth, leftHeight =	Leftchild
					
						if (currentChar == operator[0]): #Vertical slice
							stacky.push((rightWidth+leftWidth, (max(rightHeight,leftHeight))))
						elif (currentChar == operator[1]): #Horizontal slice
							stacky.push((max(rightWidth,leftWidth),rightHeight+leftHeight))
						else:
							print("Erreur AreaComputation. Invalid Operator in postfixExpression :" + postfixExpression + " " + postfixExpression[x])
				#print(stacky)
				width, height = stacky.pop()
				area = width * height
				#print("Area : " + str(area))
				if (area < BestCandidate or BestCandidate == 0):
					RealDict = flipDict
					BestCandidate = area
					RealNote = FlipNote 
			RectRotation = ""
					
			#print("Best : " + str(BestCandidate))
			ordered = OrderedDict(sorted(RealDict.items(), key=lambda t: t[0]))
			while(len(ordered) != 0):
				key, value = ordered.popitem(False)
				if(value == "1"):
					RectRotation += "0"
				elif (value =="0"):
					RectRotation += "1"
			#print(RectRotation)
			return RectRotation, BestCandidate
def eval_expr(expression):
    operand_stack = ArrayStack()
    operator_stack = ArrayStack()

    for i in range(len(expression)):
        if expression[i] == '(':
            continue
        elif expression[i] in '0123456789':
            operand_stack.push(int(expression[i]))
        elif expression[i] in '+-*/':
            operator_stack.push(expression[i])
        elif expression[i] == ')':
            op2 = operand_stack.pop()
            op1 = operand_stack.pop()
            op = operator_stack.pop()
            operand_stack.push(compute(op1,op2,op))

    return operand_stack.pop()
__author__ = 'Stephen'

# Given a string of an arithmetic expression, design an algorithm, using a stack, to evaluate it

from ArrayStack import ArrayStack
import operator


ops = {"+": operator.add, "-": operator.sub, "*": operator.mul, "/": operator.div}

arithmetic = "3 + 3"


parts = arithmetic.split()
stack = ArrayStack(len(parts))

stack.push(int(parts[0]))
stack.push(parts[1])
stack.push(int(parts[2]))

number1 = stack.pop()
op = stack.pop()
number2 = stack.pop()

stack.push(ops[op](number1, number2))

print stack
Example #45
0
__author__ = 'maskari'
from ArrayStack import ArrayStack


class StackTransfer:
    def transfer(self, s, t):
        while not s.is_empty():
            t.push(s.pop())

if __name__ == '__main__':

    st = StackTransfer()

    s1 = ArrayStack()
    s2 = ArrayStack()

    s1.push(1)
    s1.push(2)
    s1.push(3)
    # s1 = [1, 2, 3]
    print(s1)

    st.transfer(s1, s2)
    # s2 = [3, 2, 1]
    print(s2)