Example #1
0
    def __iadd__(self, other):
        selfStack = ArrayStack()
        otherStack = ArrayStack()
        result = Integer("")

        for elem in self.number:
            selfStack.push(elem)
        for i in range(len(self.number) - len(other.number)):
            otherStack.push(0)
        for elem in other.number:
            otherStack.push(elem)

        hold = 0
        for i in range(len(otherStack)):
            resultDigit = str((selfStack.pop() + otherStack.pop() + hold))

            if (len(resultDigit) == 2):
                hold = int(resultDigit[0])
                result.number.add_first(int(resultDigit[1]))
            else:
                hold = 0
                result.number.add_first(int(resultDigit))
        
        result.number.add_first(hold)
        
        while (result.number.header.next.data == 0 and len(result.number) > 1):
            result.number.delete_first()
        return result
Example #2
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 #3
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())
Example #4
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
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 #7
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 #8
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
Example #9
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
Example #10
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 #11
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 #12
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 #13
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 #14
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 #15
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 #16
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._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 #18
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 #19
0
class SortedStack:
    def __init__(self):
        self._stack = ArrayStack()

    def peek(self):
        return self._stack.peek()

    def pop(self):
        return self._stack.pop()

    def push(self, value):
        temp = ArrayStack()

        if self._stack.is_empty() or self._stack.peek() > value:
            self._stack.push(value)
        else:
            hold = value
            size = len(self._stack) + 1

            while len(self._stack) != size:
                if self.peek() < hold and self.peek() is not None:
                    temp.push(self.pop())
                elif hold is not None:
                    self._stack.push(hold)
                    hold = None
                else:
                    self._stack.push(temp.pop())
Example #20
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 #21
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 #22
0
class MaxStack:
    def __init__(self):
        self.data = ArrayStack()

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

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

    def push(self, e):
        if len(self) == 0:
            self.data.push((e, e))
        else:
            if self.data.data[-1][1] > e:
                self.data.push((e, self.data.data[-1][1]))
            else:
                self.data.push((e, e))

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

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

    def max(self):
        if (self.is_empty()):
            raise Exception("Stack is empty")
        else:
            return self.data.data[-1][1]
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 #24
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 #25
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 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)
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
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()
Example #29
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 #30
0
def permutations(lst):
    perms = ArrayStack()
    parts = ArrayQueue()
    combo = []

    for x in range(len(lst)):
        if perms.is_empty():
            perms.push([lst[x]])
        else:
            for y in range(len(perms)):
                p_lst = perms.pop()
                for z in range(len(p_lst) + 1):
                    parts.enqueue(p_lst[:z] + [lst[x]] + p_lst[z:])
            for a in range(len(parts)):
                perms.push(parts.dequeue())
    while not perms.is_empty():
        combo.append(perms.pop())
    return combo
Example #31
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 #32
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 #33
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()
Example #35
0
def postfix():
    operators = "+-*/"
    stack = ArrayStack()
    while x != 'done()':
        x = input("-->")
        if "=" in x:
            equalPosition = x.find('=')
            variable_name = ''
            for k in range(0, equalPosition - 1):
                variable_name += x[k]
            for j in range(equalPosition + 2, len(x)):
                if x[j] not in operators:
                    stack.push(int(x[j]))
                else:
                    operand_1 = stack.pop()
                    operand_2 = stack.pop()
                    if (j == '+'):
                        res = operand_2 + operand_1
                    elif (j == '-'):
                        res = operand_2 - operand_1
                    elif (j == '*'):
                        res = operand_2 * operand_1
                    else:
                        res = operand_2 / operand_1
                    stack.push(res)
        else:
            for i in x:
                if i not in operators:
                    stack.push(int(i))
                else:
                    operand_1 = stack.pop()
                    operand_2 = stack.pop()
                    if (i == '+'):
                        res = operand_2 + operand_1
                    elif (i == '-'):
                        res = operand_2 - operand_1
                    elif (i == '*'):
                        res = operand_2 * operand_1
                    else:
                        res = operand_2 / operand_1
                    stack.push(res)
            print(stack.pop())
Example #36
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 #37
0
def eval_postfix_boolean_exp(boolean_exp_str):
    lst = boolean_exp_str.split()
    stack = ArrayStack()
    for i in lst:
        if i.isdigit():
            stack.push(int(i))
        else:
            second = stack.pop()
            first = stack.pop()
            if i == "<":
                new = first < second
            elif i == ">":
                new = first > second
            elif i == "&":
                new = first and second
            elif i == "|":
                new = first or second
            stack.push(new)
    answer = stack.pop()
    return answer
 def preorder_with_stack(self):
     if (self.is_empty()):
         return
     DFS_stack = ArrayStack()
     DFS_stack.push(self.root)
     while (DFS_stack.is_empty() == False):
         curr_node = DFS_stack.pop()
         yield curr_node
         if (curr_node.right is not None):
             DFS_stack.push(curr_node.right)
         if (curr_node.left is not None):
             DFS_stack.push(curr_node.left)
Example #39
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 #40
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
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?
                
Example #42
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 #43
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()
__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