def test_from_values(self):
        st = Stack.from_values()
        self.assertEqual(len(st), 0)

        st = Stack.from_values(11, 22)
        self.assertEqual(len(st), 2)
        self.assertEqual(st.top(), 22)
 def test_push(self):
     """ self.assertRaises fails when method doesn't throw mentioned error.
         Since, exception is handled, method push() doesn'throw error. 
         Hence, assertRaises fails. Same with other below methods tests
     """
     st = Stack()
     st.push(11)
     st.push(22)
     st.push(33)
     self.assertEqual(st.top(), 33)
     self.assertEqual(len(st), 3)
     st.push(44)
     st.push(55)
Exemple #3
0
 def move_top_k(self, r_orig, c_orig, r_dest, c_dest, k):
     assert 0 <= r_orig and r_orig < self.size and 0 <= c_orig and c_orig < self.size, 'move_top_k orig out of bounds r={0}, c={1}'.format(
         r_orig, c_orig)
     assert 0 <= r_dest and r_dest < self.size and 0 <= c_dest and c_dest < self.size, 'move_top_k dest out of bounds r={0}, c={1}'.format(
         r_dest, c_dest)
     assert 0 < k and k <= len(self.board[r_orig][
                                   c_orig]), 'move_top_k number of pieces out of bounds k={0} and board has {1} pieces'.format(
         k, len(self.board[r_orig][r_dest]))
     tmp = Stack()
     for i in range(k):
         tmp.add(self.board[r_orig][c_orig].remove())
     if len(self.board[r_dest][c_dest]) > 0:
         piece_type, owner = self.board[r_dest][c_dest].top()
         if piece_type == STANDING_STONE:
             self.set_top_piece(r_dest, c_dest, FLAT_STONE, owner)
     for i in range(k):
         self.board[r_dest][c_dest].add(tmp.remove())
Exemple #4
0
def isMatched(expr):
    """Checks if the expression 'expr' has matching opening/closing symbols."""
    #a=list(expr)
    #print(a)
    #b=0
    S = Stack()
    l = len(expr)
    i = 0
    while i != l:
        symb = expr[i]
        i = i + 1

        if symb == '{' or symb == '[' or symb == '(':
            t = symb
            S.push(symb)

        elif symb == '}' or symb == ']' or symb == ')':
            if S.isEmpty():
                return False
            else:
                left = S.pop()
            if not match(left, symb):
                return False

    if S.isEmpty():
        return True
    else:
        return False
Exemple #5
0
def posteval(expr):
    operandstack = Stack()
    for i in expr.split():
        if i in string.digits:
            operandstack.push(int(i))
        else:
            sec = operandstack.pop()
            fis = operandstack.pop()
            res = eval('%d%s%d' % (fis, i, sec))
            operandstack.push(res)
    return operandstack.pop()
Exemple #6
0
def eval_postfix(s):
    """Evaluates the postfix expression 's'."""
    stack = Stack()

    s = s.split()
    for i in s:
        if operator(i) == False:
            stack.push(int(i))
        else:
            b = stack.pop()
            a = stack.pop()
            result = evaluate(a, i, b)
            stack.push(result)
    return stack.pop()
Exemple #7
0
def isMatched(expr):
    """Checks if the expression 'expr' has matching opening/closing symbols."""
    S = Stack()
    for ch in expr:
        if ch in ('(', '[', '{'):
            S.push(ch)
        elif ch in ('}', ']', ')'):
            if S.isEmpty():
                return False
            if matches(ch, S.topE()):
                S.pop()
            else:
                return False
        else:
            pass
    if S.isEmpty():
        return True
    return False
Exemple #8
0
def eval_prefix(expr):
    T = Stack()
    sp = expr.split()
    l = len(sp) - 1
    while l >= 0:
        symb = sp[l]
        l = l - 1
        if not operator(symb):
            T.push(symb)
        else:
            if T.isEmpty():
                return False
            else:
                a = T.pop()
                b = T.pop()
                c = apply(a, b, symb)
                T.push(c)
    return T.pop()
Exemple #9
0
def posteval(expr):
	operandstack = Stack()
	for i in expr.split():
		if i in string.digits:
			operandstack.push(int(i))
		else:
			sec = operandstack.pop()
			fis = operandstack.pop()
			res = eval('%d%s%d'%(fis,i,sec))
			operandstack.push(res)
	return operandstack.pop()
Exemple #10
0
def convert(expr):
    S = Stack()
    sp = expr.split()
    l = len(sp) - 1
    while l >= 0:

        symb = sp[l]
        l = l - 1
        if not operator(symb):
            S.push(symb)
        else:
            if S.isEmpty():
                return False
            else:
                a = S.pop()
                b = S.pop()
                c = a + " " + b + " " + symb
                S.push(c)
    return S.pop()
def rev_string(string):
    ''' Function rev_string
        Params: string
        Returns: the reverse of the input string
    '''
    stack = Stack()
    rev = ""

    for letter in string:
        stack.push(letter)

    while not stack.is_empty():
        rev = rev + stack.top()
        stack.pop()

    return rev
def eval_postfix(s):
    """Evaluates the postfix expression 's'."""
    S=Stack()
    l=s.split(' ')
    i=0
    while i!=len(l):
        symb=l[i]
        i=i+1
        if not operator(symb):
            S.push(symb)
        else:
            a=S.pop()
            b=S.pop()
            result=apply(symb,a,b)
            S.push(result)
    return S.pop()
def check(expr):
    s = Stack()
    index = 0
    for i in expr:
        if i in '({[':
            s.push(i)
        elif i in ')}]':
            try:
                s.pop()
            except:
                return False
    if s.isEmpty():
        return True
    else:
        return False
Exemple #14
0
def isMatched(expr):
    """Checks if the expression 'expr' has matching opening/closing symbols."""

    s = Stack()
    for char in expr:
        if char == '[' or char == '{' or char == '(':
            s.push(char)
        elif char == ']' or char == '}' or char == ')':
            if s.isEmpty():
                return False
            else:
                symbol = s.peek()
                char = invert(char)
                print("Next char is: ", char)
                if symbol == char:
                    s.pop()
                else:
                    return False

    return True
Exemple #15
0
def check(expr):
	s = Stack()
	index =0 
	for i in expr:
		if i in '({[':
			s.push(i)
		elif i in ')}]':
			try:
				s.pop()
			except:
				return False
	if s.isEmpty():
		return True
	else:
		return False
Exemple #16
0
def checking(list):
    stack = Stack()
    balanced = True
    index = 0
    while index < len(list) and balanced:
        symbol = list[index]
        if symbol in '([{':
            stack.push(symbol)
        else:
            if stack.isEmpty():
                balanced = False
            else:
                top = stack.pop()
                if not compare(top, symbol):
                    balanced = False

        index = index + 1
    if balanced and stack.isEmpty():
        return True
    else:
        return False
Exemple #17
0
def isMatched(expr):
    """Checks if the expression 'expr' has matching opening/closing symbols."""
    sp = expr.split()

    b = 0
    S = Stack()

    while b != len(sp):
        symb = sp[b]
        b = b + 1
        if symb == '{' or symb == '[' or symb == '(':
            t = symb
            S.push(symb)

        elif symb == '}' or symb == ']' or symb == ')':
            if S.isEmpty():
                return False
            else:
                left = S.pop()

                if not match(symb, left):
                    return False

    return S.isEmpty()
from mystack import Stack
#Finds whether given input paranthesis sequence is right or not.A stack application
s = Stack()

#((((()))))()


def check(expr):
    s = Stack()
    index = 0
    for i in expr:
        if i in '({[':
            s.push(i)
        elif i in ')}]':
            try:
                s.pop()
            except:
                return False
    if s.isEmpty():
        return True
    else:
        return False


print check('([{}])}')
Exemple #19
0
def infixTOPost(expr):
    S = Stack()

    sp = expr.split()
    i = 0
    res = ''
    while i != len(sp):
        symb = sp[i]
        i = i + 1
        if operand(symb):
            res = res + ' ' + symb
        elif operator(symb):
            while not S.isEmpty() and not OpeningPara(
                    S.top()) and HasHigherPre(S.top(), symb):
                res = res + ' ' + S.top()
                S.pop()
            S.push(symb)
        elif OpeningPara(symb):
            S.push(symb)
        elif ClosingPara(symb):
            while not S.isEmpty() and not OpeningPara(S.top()):
                res = res + ' ' + S.top()
                S.pop()
            S.pop()

    while not S.isEmpty():
        res = res + ' ' + S.top()
        S.pop()
    return res
Exemple #20
0
def conInfi(expr):
    sc = Stack()
    pexp = ''
    for ch in expr:
        if ch in ('*', '/', '+', '-'):
            while (sc.isEmpty() is False and Scale(sc.topE()) >= Scale(ch)):
                pexp += sc.pop() + ' '
            sc.push(ch)
        elif ch == '(':
            sc.push(ch)
        elif ch == ')':
            while (sc.isEmpty() is False and sc.topE() is not '('):
                pexp += sc.pop()
            sc.pop()
        else:
            pexp += ch + ' '

    while (not sc.isEmpty()):
        pexp += sc.pop() + ' '
    return pexp
Exemple #21
0
def infixToPostfix(infixexpr):
    prec = {}
    prec["*"] = 3
    prec["/"] = 3
    prec["+"] = 2
    prec["-"] = 2
    prec[")"] = 1
    opStack = Stack()
    postfixList = []
    tokenList = infixexpr.split()
    tokenList.reverse()
    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())

    postfixList.reverse()
    return " ".join(postfixList)
Exemple #22
0
 def __init__(self):
     """Initialize an empty stack"""
     self.stack = Stack()
     self.maxvals = Stack()
Exemple #23
0
def postfix(expr):
	optstack = Stack()
	olist = []
	for i in expr.split():
		if i is '(':
			optstack.push(i)
		elif i in string.uppercase or i in string.digits:
			olist.append(i)
		elif i is ')':
			while True:
				h=optstack.pop()
				if h == '(':
					break
				olist.append(h)
		elif i in prior.keys():
			if not optstack.isEmpty():
				if optstack.peek() == '(':
					optstack.push(i)
				else:
					while True:
						if not optstack.isEmpty():
							if prior[i]>prior[optstack.peek()]:
								optstack.push(i)
								break
							else:
								olist.append(optstack.pop())
						else:
							optstack.push(i)
							break
			else:
				optstack.push(i)

	if optstack:
		while not optstack.isEmpty():
			olist.append(optstack.pop())

	return ' '.join(olist)