def test_Stack_pushTwice(self):
     """ Push two items onto new stack. Size is now 2.
     """
     s = myStack()
     s.push(1)
     s.push(1)
     self.assertEqual(2, s.get_size())
 def test_Stack_peek(self):
     """ Peek at top item of a stack. It is last item pushed onto stack.
     """
     s = myStack()
     s.push(1)
     s.push(2)
     s.push(3)
     self.assertEqual(3, s.peek())
Пример #3
0
    def orderTraversal(self, root, key=None):
        height = self.height(root)
        stack = myStack(height)
        result = str(key(root, stack))
        while not stack.isEmpty():
            currentRoot = stack.pop()
            result += " " + str(key(currentRoot, stack))

        return result
 def test_Stack_viewEmpty(self):
     """ view() method prints warning for empty stack.
     """
     s = myStack()
     temp_stdout = StringIO()
     with contextlib.redirect_stdout(temp_stdout):
         s.view()
     output = temp_stdout.getvalue().strip()
     assert output == "Stack is empty."
 def test_Stack_pop(self):
     """ On new stack push two items, pop one. Size is now 1.
     """
     s = myStack()
     s.push(1)
     s.push(2)
     result = s.pop()
     self.assertEqual(result, 2)
     self.assertEqual(1, s.get_size())
 def test_Stack_popTwice(self):
     """ On new stack push two items, pop two. Last popped item is first item pushed. Size is now 0.
     """
     s = myStack()
     s.push(1)
     s.push(2)
     s.pop()
     result = s.pop()
     self.assertEqual(result, 1)
     self.assertEqual(0, s.get_size())
 def test_Stack_popFromEmptyStack(self):
     """ Attempt to pop another item from now empty stack. Warning message is printed. return value is None.
     """
     s = myStack()
     s.push(1)
     s.push(2)
     s.push(3)
     s.pop()
     s.pop()
     s.pop()
     temp_stdout = StringIO()
     with contextlib.redirect_stdout(temp_stdout):
         result = s.pop()
     output = temp_stdout.getvalue().strip()
     assert output == "Cannot pop from an empty stack."
     self.assertEqual(result, None)
Пример #8
0
def check(value):
    """
	This function checks if the list of brackets are correct

	Parameters
	----------
	value : list
		list of brackets
		
	Return
	------
	message : string
		if the list is correct the fuction returns "correct"
		
		if the list has invalid values the function returns an error
			including the first found invalid value
		
		if the list has invalid bracket usage, 
			the function will return the open brackets on the stack

	Example
	-------
	>>> #value = ['(',')']
	>>> return = "Correct"

	"""
    brackets = {')': '(', '>': '<', ']': '['}
    stack = myStack()
    for i in value:
        if i in brackets.values():
            stack.push(i)
        elif i in brackets.keys():
            # if brackets[i] != stack.pop():
            # return False
            for x in brackets.keys():
                if i == x:
                    stack.pop()

        else:
            print("ERROR: '%s' not accepted" % i)
            return False

    if stack.isEmpty():
        return True
    else:
        print(stack.show())
        return str(stack.show())
Пример #9
0
def reverseK(queue, k):
    # Write your code here
    mstack = myStack()
    cnt = 0

    while cnt < k:
        mstack.push(queue.dequeue())
        cnt += 1

    while not mstack.isEmpty():
        queue.enqueue(mstack.pop())

    totSize = len(queue.queueList)
    print(totSize)

    for x in range(totSize - k):
        queue.enqueue(queue.dequeue())
Пример #10
0
def parenthesisChecker(str):
    parenthesis = {
        "[": {
            "type": 1,
            "state": "open"
        },
        "]": {
            "type": 1,
            "state": "close"
        },
        "{": {
            "type": 2,
            "state": "open"
        },
        "}": {
            "type": 2,
            "state": "close"
        },
        "(": {
            "type": 3,
            "state": "open"
        },
        ")": {
            "type": 3,
            "state": "close"
        },
    }
    stack = myStack(len(str))
    for s in str:
        if s in parenthesis:
            if parenthesis[s]["state"] == "open":
                stack.push(s)
            elif parenthesis[s]["state"] == "close":
                lastP = stack.pop()
                if parenthesis[lastP]["type"] != parenthesis[s][
                        "type"] or parenthesis[lastP]["state"] == parenthesis[
                            s]["state"]:
                    return "Not balanced"

    if stack.isEmpty():
        return "Balanced"
    else:
        "Not balanced"
Пример #11
0
def DFS(G):
    S = myStack.myStack()
    L = {}
    S.push(0)
    L[0] = 0
    i = S.top()
    while S.length != 0:
        j = get_adjacent_vertex(G, i, S, L)
        if j > 0:
            S.push(j)
            i = S.top()
        if j == -1:
            if i == 0:
                break
            else:
                L[i] = S.underTop()
                S.pop()
                i = S.top()
    return L
Пример #12
0
def isBalanced(exp):
    # Write your code here
    md = {'(': ')', '[': ']', '{': '}'}
    print(exp)
    print('--------')
    stk = myStack()
    for x in exp:
        if x in ('(', '[', '{'):
            stk.push(md.get(x))

        if x in (')', ']', '}'):
            rside = stk.pop()

            if (x != rside):
                return False

    if not stk.isEmpty():
        return False

    return True
Пример #13
0
def IsTreeSymmetric(t1, t2):
    t1InOrder = t1.inOrderTraversal().split(" ")
    t2InOrder = t2.inOrderTraversal().split(" ")
    t2InverseOrder = t2.inverseInOrderTraversal().split(" ")
    indexT1InOrder = indexT2InOrder = indexT2InverseOrder = 0
    usingInverse = True if t1InOrder[1] == t2InverseOrder[1] else False
    notFound = False
    rootVal = myStack(len(t1InOrder))
    rootVal.push(t1InOrder[0])
    while indexT1InOrder < len(t1InOrder):
        if usingInverse:
            if indexT2InverseOrder < len(t2InverseOrder) and t1InOrder[
                    indexT1InOrder] == t2InverseOrder[indexT2InverseOrder]:
                indexT2InverseOrder += 1
                notFound = False
            else:
                if notFound == True:
                    return False
                indexT2InOrder = t2InOrder.index(
                    t1InOrder[indexT1InOrder - 1]) + 1
                rootVal = t1InOrder[indexT1InOrder - 1]
                indexT1InOrder -= 1
                usingInverse = False
                notFound = True
        else:
            if indexT2InOrder < len(t2InOrder) and t1InOrder[
                    indexT1InOrder] == t2InOrder[indexT2InOrder]:
                indexT2InOrder += 1
                notFound = False
            else:
                if notFound == True:
                    return False
                indexT2InverseOrder = t2InverseOrder.index(
                    t1InOrder[indexT1InOrder - 1]) + 1
                indexT1InOrder -= 1
                usingInverse = True
                notFound = True

        indexT1InOrder += 1

    return True
Пример #14
0
 def __init__(self, stackSize, numStacks):
     self.eachCapacity = stackSize
     self.numPlates = numStacks
     self.stacks = [myStack(stackSize) for x in range(numStacks)]
 def test_StackEmpty_peek(self):
     """ peek() method return value is None for empty stack."""
     s = myStack()
     self.assertIsNone(s.peek())
 def test_Stack_push(self):
     """ Push an item onto new stack. Size is now 1.
     """
     s = myStack()
     s.push(1)
     self.assertEqual(1, s.get_size())
 def test_Stack_newEmpty(self):
     """ is_empty() method returns True for new stack.
     """
     s = myStack()
     self.assertTrue(s.is_empty())
Пример #18
0
from myStack import myStack

d = myStack()
print(d.peek())

d.push(2)
print(d.peek())

d.push(3)
print(d.peek())

d.pop()
print(d.peek())

b = d.isEmpty()
print(b)
Пример #19
0
def Getmap(s):
    j=0
    expression=''
    expression=s
    mymap=[]
    node=Node()
    nowId=0
    s_st=myStack()
    s_ed=myStack()
    s_str=myStack()

    s_str.push('$')
    
    s_st.push(nowId)
    nowId=nowId+1
    s_ed.push(nowId)
    nowId=nowId+1

    for i in expression:
        
        ch=expression[j]
        if ch=='(':
            
            s_ed.push(nowId)
            nowId=nowId+1
            s_str.push('(')
        elif ch==')':
            ed=s_ed.top()
            st=s_st.top()
            node=Node()
            node.getadd(str(st),'-',str(ed))
            mymap.append(node)
            #print(str(st)+'-'+str(ed))
            ch=s_str.top()
            while ch != '(':
                nxt=s_st.top()
                s_st.pop()
                pre=s_st.top()
                if ch !='#':
                    node=Node()
                    node.getadd(str(pre),ch,str(nxt))
                    mymap.append(node)
                    #print(str(pre)+ch+str(nxt))
                s_str.pop()
                ch=s_str.top()
            s_str.pop()
            s_str.push('#')
            top_num=s_ed.top()
            s_st.push(top_num)
            s_ed.pop()
        elif ch=='|':
            ed=s_ed.top()
            st=s_st.top()
            node=Node()
            node.getadd(str(st),'-',str(ed))
            mymap.append(node)
            #print(str(st)+"-"+str(ed))
            ch=s_str.top()
            while ch !='(' and ch!='$':
                nxt=s_st.top()
                s_st.pop()
                pre=s_st.top()
                if ch !='#':
                    node=Node()
                    node.getadd(str(pre),ch,str(nxt))
                    mymap.append(node)
                    #print(str(pre)+ch+str(nxt))
                s_str.pop()
                ch=s_str.top()
        elif ch=='*':
            nxt=s_st.top()
            s_st.pop()
            pre=s_st.top()

            node=Node()
            node.getadd(str(pre),'-',str(nxt))
            mymap.append(node)
            #print(str(pre)+"-"+str(nxt))
            node=Node()
            node.getadd(str(nxt),'-',str(pre))
            mymap.append(node)
            #print(str(nxt)+"-"+str(pre))

            s_st.push(nxt)
        else:
            s_str.push(ch)
            
            s_st.push(nowId)
            nowId=nowId+1
        j=j+1

        
    ch=s_str.top()
    while ch!='$':
        nxt=s_st.top()
        s_st.pop()
        pre=s_st.top()
        if ch !='#':
            node=Node()
            node.getadd(str(pre),ch,str(nxt))
            mymap.append(node)
            #print(str(pre)+ch+str(nxt))
        s_str.pop()
        ch=s_str.top()
    
    return mymap
precedence = (
    ('left', 'TkThen'),
    ('left', 'TkAnd', 'TkOr', 'TkElse'),
    ('right', 'TkNot', 'TkBegin'),  # Unary minus operator
)

# import some required globals from tokenizer
tokens = lexer.tokens
ParserErrors = []

procedures = ModelProcedure()

newWorld = Any

stack = myStack()
stack.push_empty_table()

programBlock = []
createdWorlds = []
objectsInWorlds = []
booleansOfWorlds = []
tasks = []

howManyTask = 0
activeWorld = Any
currentTask = Any

worldInstBool = False
taskBool = False
defineAsBool = False