Пример #1
0
def paths_with_sum(n, root):
    num_paths = 0

    itinerary = MyStack()
    itinerary.push((root, []))

    while not itinerary.isEmpty():
        v, old_sums = itinerary.pop()
        new_sums = [v.value]

        if v.value == n:
            num_paths += 1

        for s in old_sums:
            t = s + v.value
            if t == n:
                num_paths += 1
            new_sums.append(t)

        if v.right is not None:
            itinerary.push((v.right, new_sums))
        if v.left is not None:
            itinerary.push((v.left, new_sums))

    return num_paths
Пример #2
0
def paths_with_sum(n, root):
    num_paths = 0

    itinerary = MyStack()
    itinerary.push((root, []))

    while not itinerary.isEmpty():
        v, old_sums = itinerary.pop()
        new_sums = [v.value]

        if v.value == n:
            num_paths += 1

        for s in old_sums:
            t = s + v.value
            if t == n:
                num_paths += 1
            new_sums.append(t)

        if v.right is not None:
            itinerary.push((v.right, new_sums))
        if v.left is not None:
            itinerary.push((v.left, new_sums))

    return num_paths
Пример #3
0
    def test_1(self):
        items = [2, 3, 4, 5, 1, 3, 5, 7, 8, 2, 9]
        stack = MyStack()
        for item in items:
            stack.push(item)
        sort_stack(stack)

        result = []
        while not stack.isEmpty():
            result.append(stack.pop())
        self.assertEqual(result, sorted(items))
Пример #4
0
    def push(self, item):
        latest_length = self.lengths.peek()

        if (latest_length is None) or (latest_length == self.threshold):
            new_stack = MyStack()
            new_stack.push(item)
            self.stacks.push(new_stack)
            self.lengths.push(1)
        else:
            latest_stack = self.stacks.peek()
            latest_stack.push(item)
            self.lengths.push(self.lengths.pop() + 1)
Пример #5
0
    def push(self, item):
        latest_length = self.lengths.peek()

        if (latest_length is None) or (latest_length == self.threshold):
            new_stack = MyStack()
            new_stack.push(item)
            self.stacks.push(new_stack)
            self.lengths.push(1)
        else:
            latest_stack = self.stacks.peek()
            latest_stack.push(item)
            self.lengths.push(self.lengths.pop() + 1)
Пример #6
0
 def __init__(self):
     self.moves_stack = []
     for i in range(0, 3):
         self.stacks.append(MyStack(i))
     stack1 = self.stacks[0]
     for j in range(5, 0, -1):
         stack1.push(j)
Пример #7
0
def DoStackOps():
    print("\n*** Stack Ops")
    myStack = MyStack()
    print("\n\tPushing 1,2,3 on the stack")
    myStack.push(1)
    myStack.push(2)
    myStack.push(3)

    print("\t\t MyStack:", myStack)

    print("\tPoping the stack")
    print("\t\tPopped value:", myStack.pop())
    print("\t\tStack now has:", myStack)

    myStack = MyStack(['a', 'b', 'c', 'd'])
    print(f"\n\tmyStack using initializer: \n\t\t{myStack}")
Пример #8
0
class MyQueue(object):
    def __init__(self):
        self._enstack = MyStack()
        self._destack = MyStack()
        self._mode = "ENQUEUE"

    def isEmpty(self):
        return self._enstack.isEmpty() and self._destack.isEmpty()

    def _shift(self, source, target):
        while not source.isEmpty():
            target.push(source.pop())

    def _enmode(self):
        if self._mode == "DEQUEUE":
            self._shift(self._destack, self._enstack)
            self._mode = "ENQUEUE"

    def _demode(self):
        if self._mode == "ENQUEUE":
            self._shift(self._enstack, self._destack)
            self._mode = "DEQUEUE"

    def enqueue(self, item):
        self._enmode()
        self._enstack.push(item)

    def dequeue(self):
        self._demode()
        return self._destack.pop()

    def peek(self):
        self._demode()
        return self._destack.peek()
Пример #9
0
class MyQueue(object):
    def __init__(self):
        self._enstack = MyStack()
        self._destack = MyStack()
        self._mode = "ENQUEUE"

    def isEmpty(self):
        return self._enstack.isEmpty() and self._destack.isEmpty()

    def _shift(self, source, target):
        while not source.isEmpty():
            target.push(source.pop())

    def _enmode(self):
        if self._mode == "DEQUEUE":
            self._shift(self._destack, self._enstack)
            self._mode = "ENQUEUE"

    def _demode(self):
        if self._mode == "ENQUEUE":
            self._shift(self._enstack, self._destack)
            self._mode = "DEQUEUE"

    def enqueue(self, item):
        self._enmode()
        self._enstack.push(item)

    def dequeue(self):
        self._demode()
        return self._destack.pop()

    def peek(self):
        self._demode()
        return self._destack.peek()
Пример #10
0
def sort_stack(stack):
    data = stack.pop()
    sorted_stack = MyStack(data)
    while not stack.is_empty():
        data = stack.pop()
        count = 0
        while not sorted_stack.is_empty() and data < sorted_stack.peek() :
            stack.push(sorted_stack.pop())
            count += 1
        for _ in range(count):
            sorted_stack.push(stack.pop())
    return sorted_stack
Пример #11
0
class TestMyStack(unittest.TestCase):

	def setUp(self):
		print "=========== Running Stack Test ==========="
		self.s = MyStack()
	
	def tearDown(self):
		print "==========================================="

	def test_push_appends(self):
		# Unit test of push command
		# State before: Empty Stack
		# State after: Empty Stack

		self.s.push(1)
		self.assertTrue(self.s.l.pop(), 1)

	def test_pop_removes(self):
		# Unit test of pop command
		# State before: Empty Stack
		# State after: Empty Stack

		self.s.push(1)
		self.s.l.append(1)
		self.assertTrue(self.s.pop(), 1)

	def test_10_elements(self):
		# Comprehensive test, add and remove 10 elements, ensure they are popped in the correct order for a stack
		# State before: Empty Stack
		# State after: Empty Stack
		
		in_elements = []
		out_elements = []

		for i in range(0,10):
			print "Pushing %d onto stack" % i
			self.s.push(i)
			in_elements.append(i)
		for i in range(0,10):
			popped = self.s.pop()
			out_elements.append(popped)
			print "Popping %d off stack" % popped

		# Reverse out_elements because we expect the opposite order returned off the stack
		out_elements.reverse()
		self.assertEqual(in_elements, out_elements)
Пример #12
0
    def test_1(self):
        items = [2, 3, 4, 5, 1, 3, 5, 7, 8, 2, 9]
        stack = MyStack()
        for item in items:
            stack.push(item)
        sort_stack(stack)

        result = []
        while not stack.isEmpty():
            result.append(stack.pop())
        self.assertEqual(result, sorted(items))
Пример #13
0
    def test_sort_stack(self):
        for case, actual in self.data:
            case.reverse()
            actual.reverse()
            stack = MyStack(case[0])
            for i in case[1:]:
                stack.push(i)

            ans = MyStack(actual[0])
            for i in actual[1:]:
                ans.push(i)

            test = sort_stack(stack)

            while not stack.is_empty() and not ans.is_empty():
                self.assertEqual(test.pop(), ans.pop())
Пример #14
0
 def __init__(self):
     self.stack = MyStack()
     self.mins = MyStack()
Пример #15
0
 def __init__(self, threshold):
     self.threshold = threshold
     self.stacks = MyStack()
     self.lengths = MyStack()
 def __init__(self):
     self.__stack = MyStack()
Пример #17
0
class MinStack(MyStack):
    def __init__(self):
        self.stack = MyStack()
        self.mins = MyStack()

    def isEmpty(self):
        return self.stack.isEmpty()

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

    def min(self):
        return self.mins.peek()

    def pop(self):
        self.mins.pop()
        return self.stack.pop()

    def push(self, item):
        current_min = self.min()
        if (current_min is None) or (item < current_min):
            self.mins.push(item)
        else:
            self.mins.push(current_min)

        self.stack.push(item)
Пример #18
0
from MyStack import MyStack

stack = MyStack()
stack.push(1)
stack.push(2)
stack.push(3)
print(str(stack.peek()))
stack.push(4)
stack.push(5)
stack.push(6)
print(str(stack.peek()))
print(str(stack))
stack.pop()
stack.pop()
stack.pop()
stack.pop()
print(str(stack.peek()))
print(str(stack))
class RPNCalculator:
    __input_data = ""
    __stack = None

    def __init__(self):
        self.__stack = MyStack()

    def __process_inpuit_data(self):
        args = re.split(r"\s{1,}", self.__input_data.strip())
        #print(args)
        try:
            for each in args:
                if each == "+":
                    num1 = self.__stack.pop()
                    num2 = self.__stack.pop()
                    self.__stack.push(num1 + num2)
                elif each == "-":
                    num1 = self.__stack.pop()
                    num2 = self.__stack.pop()
                    self.__stack.push(num2 - num1)
                elif each == "*":
                    num1 = self.__stack.pop()
                    num2 = self.__stack.pop()
                    self.__stack.push(num1 * num2)
                elif each == "/":
                    num1 = self.__stack.pop()
                    num2 = self.__stack.pop()
                    self.__stack.push(num2 / num1)
                elif each == "sin":
                    num1 = self.__stack.pop()
                    self.__stack.push(math.sin(num1))
                elif each == "cos":
                    num1 = self.__stack.pop()
                    self.__stack.push(math.cos(num1))
                elif each == "sqrt":
                    num1 = self.__stack.pop()
                    self.__stack.push(math.sqrt(num1))
                elif each == "d":
                    print("degree mode")
                    num1 = self.__stack.pop()
                    self.__stack.push(num1 / 180 * math.pi)
                else:
                    num = float(each)
                    self.__stack.push(num)
        except ValueError:
            while not self.__stack.is_empty():
                self.__stack.pop()
            self.__stack.push("Cannot convert input to number.")
        except IndexError:
            while not self.__stack.is_empty():
                self.__stack.pop()
            self.__stack.push("Math Error!")

    def input_work(self, input_data):
        self.__input_data += input_data

    def get_result(self):
        self.__process_inpuit_data()
        return self.__stack.pop()
Пример #20
0
def findWords(firstWord, lastWord):
    global dictionary

    #---------------Enter your source code here----------------#
    #Print a shortest word ladder for the firstWord and lastWord and return 1 if such a ladder can be found
    #Return -1 if there exists no word ladder for the firstWord and lastWord

    usedWords = []
    usedWords.append(firstWord)
    #step 1
    count = 0
    breakFirstWordIntoChars = list(firstWord)
    myQueue = MyQueue()

    for i in range(len(dictionary)):

        if len(dictionary[i]) == len(breakFirstWordIntoChars):
            breakDicObjectIntoChars = list(dictionary[i])
            for j in range(len(breakFirstWordIntoChars)):

                if breakFirstWordIntoChars[j] != breakDicObjectIntoChars[j]:
                    count += 1

            if count == 1 and dictionary[i] not in usedWords:
                myStack = MyStack()
                myStack.push(firstWord)
                myStack.push(dictionary[i])
                usedWords.append(dictionary[i])
                myQueue.enqueue(myStack)

        count = 0

    #step 2
    #print myQueue.size()

    if myQueue.size() > 0:
        count = 0

        while (True):

            if myQueue.isEmpty() is not True:
                firstStack = myQueue.dequeue()
                firstStackWord = firstStack.peek()

                print firstStack.toString()
                if firstStackWord == lastWord:
                    #return firstStack.toString()
                    break
                else:

                    firstStackWordIntoChars = list(firstStackWord)

                    for m in range(len(dictionary)):
                        if len(dictionary[m]) == len(firstStackWordIntoChars):
                            breakDicObjectIntoChars = list(dictionary[m])

                            for n in range(len(firstStackWordIntoChars)):
                                if firstStackWordIntoChars[
                                        n] != breakDicObjectIntoChars[n]:
                                    count += 1

                            if count == 1 and dictionary[m] not in usedWords:
                                myStack2 = MyStack()
                                myStack2.copyFrom(firstStack)
                                myStack2.push(dictionary[m])
                                myQueue.enqueue(myStack2)
                                usedWords.append(dictionary[m])

                        count = 0
            else:

                return -1
                break
    else:
        myStack2 = MyStack()
        myStack2.push(firstWord)
        return myStack2.toString()
Пример #21
0
 def __init__(self):
     self._enstack = MyStack()
     self._destack = MyStack()
     self._mode = "ENQUEUE"
Пример #22
0
def findWords(firstWord, lastWord):
    global dictionary

    #---------------Enter your source code here----------------#
    #Print a shortest word ladder for the firstWord and lastWord and return 1 if such a ladder can be found
    #Return -1 if there exists no word ladder for the firstWord and lastWord

    queue = MyQueue()  #declare a new queue
    existingwordlist = []  #to keep track of used words
    firtFound = False
    lastFound = False
    # if both words exist in dictionary, then posible to have ladder
    for i in range(len(dictionary)):
        if firstWord == dictionary[i]:
            firstFound = True
        if lastWord == dictionary[i]:
            lastFound = True
    if lastFound and firstFound:
        if firstWord == lastWord:
            print[firstWord]
            return 1
        elif len(firstWord) != len(lastWord):
            return -1
        else:
            existingwordlist.append(firstWord)
            refStack = MyStack()
            refStack.push(firstWord)
            whileCounter = 0
            curword = firstWord
            while lastWord not in existingwordlist and whileCounter < 100:
                queuedCount = 0
                for i in range(len(dictionary)):  #go through dictionary list
                    if len(curword) == len(
                            dictionary[i]):  #if word length matches
                        counter = 0
                        for k in range(len(curword)):
                            a = dictionary[i]
                            if a[k] == curword[
                                    k]:  #go through each character and match if they are the same
                                counter += 1

                        if counter == (len(dictionary[i]) - 1) and dictionary[
                                i] not in existingwordlist:  #do checking if only one letter different
                            existingwordlist.append(dictionary[i])
                            curStack = MyStack()
                            curStack.copyFrom(refStack)
                            curStack.push(dictionary[i])
                            queue.enqueue(
                                curStack)  #enqueue the stack into the queue
                            queuedCount += 1

                if queuedCount == 0 and queue.size() > 0:
                    refStack = MyStack()
                    firstStack = queue.dequeue()
                    refStack.copyFrom(firstStack)
                    curword = firstStack.pop()
                whileCounter += 1  # can't think of any smarter way to prevent infinite loop
            outputlist = []  #declare a list to store the word ladder
            if lastWord in existingwordlist:
                for k in range(queue.size()):
                    outputlist.append(queue.dequeue().toString())
                print(outputlist[-1])
                return 1
            else:
                return -1
    else:
        return -1
Пример #23
0
'''
Created on 19 Feb. 2018

@author: Amit.Kumar1
'''

from MyStack import MyStack

my_stack = MyStack(10)
val = 1
while (my_stack.full() == False):
    my_stack.push(val)
    val += 1
while (my_stack.empty() == False):
    print(my_stack.pop())

Пример #24
0
def sort_stack(stack):
    sorter = MyStack()
    while not stack.isEmpty():
        holder = stack.pop()

        if sorter.isEmpty():
            sorter.push(holder)
        else:
            counter = 0
            while (not sorter.isEmpty()) and (sorter.peek() > holder):
                stack.push(sorter.pop())

            sorter.push(holder)

            for _ in range(counter):
                sorter.push(stack.pop())

    while not sorter.isEmpty():
        stack.push(sorter.pop())
Пример #25
0
 def __init__(self):
     self.stack = MyStack()
     self.mins = MyStack()
Пример #26
0
class MyStackTest(unittest.TestCase):
	def setUp(self):
		self.start_time = time.perf_counter()
		self.stack = MyStack()

	def tearDown(self):		
		t = time.perf_counter() - self.start_time
		test_id = self.id().split(".")[-1]
		
		if t < 0.1:
			t = t * 1000
			print("{}: {:.3f}ms".format(test_id, t))
		else:
			print("{}: {:.3f}s".format(test_id, t))
		#self.stack.clear()

	@nottest
	def test_push_peek(self):
		self.stack.push("right")
		self.assertEqual(self.stack.peek(), "right")

	def test_push_pop_emptycheck(self):
		self.stack.push(1)
		num = self.stack.pop()
		self.assertEqual(num, 1)
		self.assertTrue(self.stack.is_empty())

	# only work under linux because of SIGALRM not work in windows
	#@timeout_decorator.timeout(0.5)
	def test_large_num_push_pop(self):
		for i in range(100001):
			self.stack.push(i)

		for i in range(100000, 0, -1):
			#without using subTest, the test will stop when the first fail happened
			#with subTest, all test will be performed and failure ones will be presented separately
			# if i == 9983:
			# 	i += 1
			with self.subTest(i = i):
				self.assertEqual(i, self.stack.pop())
				self.assertFalse(self.stack.is_empty())

		self.stack.pop()
		self.assertTrue(self.stack.is_empty())

		with self.assertRaises(IndexError):
			self.stack.pop()
Пример #27
0
 def __init__(self):
     self._enstack = MyStack()
     self._destack = MyStack()
     self._mode = "ENQUEUE"
Пример #28
0
	def setUp(self):
		self.start_time = time.perf_counter()
		self.stack = MyStack()
Пример #29
0
class MyListener(LittleListener):

    # Create a dictionary to hold the symbol table
    global symbolTable
    symbolTable = collections.OrderedDict()

    # Stack to track of which scope we are in for the symbol table
    global stack
    stack = MyStack()

    # Stack used to build the ast tree
    global ast_stack
    ast_stack = MyStack()

    # Global block variable to count Block scopes
    block = 0

    # Global flag variable to indicate declaration errors
    global flag
    flag = False

    # Global list to store repeated variable names
    # Currently only using the first entry in this list
    global errorNames
    errorNames = []

    # error method to set flag to true when an error is found
    def error(self):
        global flag
        flag = True

    # getError method to return error message as string
    def getError(self, name):
        return "DECLARATION ERROR " + name

    # creates a new symbol table scope
    def enterScope(self, name):
        scope_dict = collections.OrderedDict()

        symbolTable[name] = collections.OrderedDict()
        stack.push(name)

    # pops the current scope off the stack
    def exitScope(self):
        if stack.isEmpty():
            pass
        else:
            popped_scope = stack.pop()

    def getCurrentScope(self):
        return stack.peek()

    # Return the Symbol Table created
    def getTable(self):
        return symbolTable

    # Pretty print for the symbol table
    def printTable(self):
        if flag:
            print(self.getError(errorNames[0]))
        else:
            for scope, values in symbolTable.items():
                print("Symbol table " + scope)
                if values:
                    for var_name in values:
                        if values[var_name][0] == "STRING":
                            print("name " + var_name + " type " +
                                  values[var_name][0] + " value " +
                                  values[var_name][1])
                        else:
                            print("name " + var_name + " type " +
                                  values[var_name][0])

    # Creates numbered block names for conditionals
    def getScopeNum(self):
        global block
        self.block += 1
        name = str(self.block)
        return name

    def getStack(self):
        return ast_stack

    # Scope Declaration Functions
    def enterProg(self, ctx: LittleParser.ProgContext):
        self.enterScope("GLOBAL")

    # Exit a parse tree produced by LittleParser#prog.
    def exitProg(self, ctx: LittleParser.ProgContext):
        self.exitScope()

    ############ START OF AST TREE WALKING ##########################

    # Enter a parse tree produced by LittleParser#func_decl.
    def enterFunc_decl(self, ctx: LittleParser.Func_declContext):
        name = ctx.getChild(2).getText()
        self.enterScope(name)
        ast_stack.push(ASTNode(node_enum(10).name, name))

    # Exit a parse tree produced by LittleParser#func_decl.
    def exitFunc_decl(self, ctx: LittleParser.Func_declContext):
        self.exitScope()

    # Enter a parse tree produced by LittleParser#if_stmt.
    def enterIf_stmt(self, ctx: LittleParser.If_stmtContext):
        num = self.getScopeNum()
        name = "BLOCK " + num
        self.enterScope(name)
        ast_stack.push(ASTNode(node_enum(10).name, "label" + num))

    # Exit a parse tree produced by LittleParser#if_stmt.
    def exitIf_stmt(self, ctx: LittleParser.If_stmtContext):
        self.exitScope()
        if_node = ASTNode(node_enum(13).name, [], "")
        end_node = ASTNode(node_enum(16).name, [])

        else_node = ast_stack.pop()
        sl_node = ast_stack.pop()
        comp_node = ast_stack.pop()

        if_label = ast_stack.pop()
        end_label = ASTNode(node_enum(10).name, "label" + self.getScopeNum())

        end_node.value.append(if_label)
        end_node.value.append(end_label)
        end_node.val_type = 'if'

        if_node.val_type = if_label
        if_node.value.append(comp_node)
        if_node.value.append(sl_node)

        # if not a placeholder node,
        # assign the else label to the cop_op node, add the end node to the else values
        # add else node to the end of if's value list
        if else_node.node_type != node_enum(6).name:
            eend_node = ASTNode(node_enum(16).name, [if_label, end_label])
            eend_node.val_type = 'else'
            else_label = else_node.val_type
            comp_node.val_type = else_label
            else_node.value.append(end_node)
            if_node.value.append(eend_node)
            if_node.value.append(else_node)
        else:
            comp_node.val_type = end_label

        if_node.value.append(end_node)
        ast_stack.push(if_node)

    # Enter a parse tree produced by LittleParser#else_part.
    def enterElse_part(self, ctx: LittleParser.Else_partContext):
        if ctx.getChildCount() == 0:
            node = ASTNode(node_enum(6).name, "")  #Placeholder node
            ast_stack.push(node)
        else:
            num = self.getScopeNum()
            name = "BLOCK " + num
            self.enterScope(name)
            ast_stack.push(ASTNode(node_enum(10).name, "label" + num))

    # Exit a parse tree produced by LittleParser#else_part.
    def exitElse_part(self, ctx: LittleParser.Else_partContext):
        self.exitScope()
        if ast_stack.peek().node_type == node_enum(6).name:
            pass
        else:
            stmtList = ast_stack.pop()
            label = ast_stack.pop()
            node = ASTNode(node_enum(15).name, [stmtList], label)
            ast_stack.push(node)

    # Enter a parse tree produced by LittleParser#while_stmt.
    def enterWhile_stmt(self, ctx: LittleParser.While_stmtContext):
        num = self.getScopeNum()
        name = "BLOCK " + num
        self.enterScope(name)
        ast_stack.push(ASTNode(node_enum(10).name, "label" + num))

    # Exit a parse tree produced by LittleParser#while_stmt.
    def exitWhile_stmt(self, ctx: LittleParser.While_stmtContext):
        self.exitScope()

        while_node = ASTNode(node_enum(14).name, [])
        end_node = ASTNode(node_enum(16).name, [])
        end_label = ASTNode(node_enum(10).name, "label" + self.getScopeNum())

        # grab nodes from the stack needed to create a WHILE node
        stmt_list = ast_stack.pop()
        comp_op = ast_stack.pop()  # add the end label to the comp-op node
        comp_op.val_type = end_label

        w_label = ast_stack.pop()

        # END node contains the while label and the endwhile label
        end_node.value.append(w_label)
        end_node.value.append(end_label)
        end_node.val_type = 'while'

        # WHILE.value = [comp_op, stmt_list, end]
        while_node.value.append(comp_op)
        while_node.value.append(stmt_list)
        while_node.value.append(end_node)
        while_node.val_type = w_label

        ast_stack.push(while_node)

    # Enter a parse tree produced by LittleParser#var_decl.
    def enterVar_decl(self, ctx: LittleParser.Var_declContext):
        v_type = ctx.getChild(0).getText()
        name_list = ctx.getChild(1).getText().split(',')
        scope = stack.peek()
        for n in name_list:
            if n in symbolTable[scope]:
                self.error()
                errorNames.append(n)
            else:
                symbolTable[scope][n] = (v_type, '')

    # Exit a parse tree produced by LittleParser#var_decl.
    def exitVar_decl(self, ctx: LittleParser.Var_declContext):
        pass

    # Enter a parse tree produced by LittleParser#string_decl.
    def enterString_decl(self, ctx: LittleParser.String_declContext):
        v_type = ctx.getChild(0).getText()
        name = ctx.getChild(1).getText()
        val = ctx.getChild(3).getText()
        scope = stack.peek()
        symbolTable[scope][name] = (v_type, val)

    # Exit a parse tree produced by LittleParser#string_decl.
    def exitString_decl(self, ctx: LittleParser.String_declContext):
        pass

    # Enter a parse tree produced by LittleParser#param_decl.
    def enterParam_decl(self, ctx: LittleParser.Param_declContext):
        v_type = ctx.getChild(0).getText()
        name = ctx.getChild(1).getText()
        if v_type == "STRING":
            val = ctx.getChild(3).getText()
        else:
            val = ''
        scope = stack.peek()
        symbolTable[scope][name] = (v_type, val)

    # Exit a parse tree produced by LittleParser#param_decl.
    def exitParam_decl(self, ctx: LittleParser.Param_declContext):
        pass

    # Enter a parse tree produced by LittleParser#addop.
    def enterAddop(self, ctx: LittleParser.AddopContext):
        node = ASTNode(node_enum(1).name, ctx.getChild(0).getText())
        ast_stack.push(node)

    # Exit a parse tree produced by LittleParser#addop.
    def exitAddop(self, ctx: LittleParser.AddopContext):
        pass

    # Enter a parse tree produced by LittleParser#expr_prefix.
    def enterExpr_prefix(self, ctx: LittleParser.Expr_prefixContext):
        # If the expr_prefix has no children(is NULL) add a Null node to the stack
        if ctx.getChildCount() != 0 and ctx.getChild(0).getChildCount() == 0:
            node = ASTNode(node_enum(0).name, "")  #NullNode
            ast_stack.push(node)
        elif ctx.getChildCount() == 0:
            node = ASTNode(node_enum(6).name, "")  #Placeholder node
            ast_stack.push(node)

    # Exit a parse tree produced by LittleParser#expr_prefix.
    def exitExpr_prefix(self, ctx: LittleParser.Expr_prefixContext):

        if ast_stack.peek().node_type == node_enum(
                6).name:  # if a placeholder node
            ast_stack.pop()
        else:
            addop_node = ast_stack.pop()
            factor_node = ast_stack.pop()
            prefix_node = ast_stack.pop()

            if prefix_node.node_type == node_enum(0).name:
                addop_node.leftChild = factor_node

            else:
                prefix_node.rightChild = factor_node
                addop_node.leftChild = prefix_node

            ast_stack.push(addop_node)

    # Enter a parse tree produced by LittleParser#factor.
    def enterFactor(self, ctx: LittleParser.FactorContext):
        if ctx.getChild(0).getChildCount() == 0:
            ast_stack.push(ASTNode(node_enum(0).name, ""))  #push

    # Exit a parse tree produced by LittleParser#factor.
    def exitFactor(self, ctx: LittleParser.FactorContext):
        postfix_node = ast_stack.pop()

        factor_prefix_node = ast_stack.pop()
        if factor_prefix_node.node_type == node_enum(0).name:
            ast_stack.push(postfix_node)

        else:
            factor_prefix_node.rightChild = postfix_node
            ast_stack.push(factor_prefix_node)

    # Enter a parse tree produced by LittleParser#assign_stmt.
    def enterAssign_stmt(self, ctx: LittleParser.Assign_stmtContext):
        pass

    # Exit a parse tree produced by LittleParser#assign_stmt.
    def exitAssign_stmt(self, ctx: LittleParser.Assign_stmtContext):
        pass

    # Enter a parse tree produced by LittleParser#factor_prefix.
    def enterFactor_prefix(self, ctx: LittleParser.Factor_prefixContext):
        # If the expr_prefix has no children(is NULL) add a Null node to the stack
        if ctx.getChildCount() != 0 and ctx.getChild(0).getChildCount() == 0:
            node = ASTNode(node_enum(0).name, "")  #NullNode
            ast_stack.push(node)
        elif ctx.getChildCount() == 0:
            node = ASTNode(node_enum(6).name, "")  #Placeholder node
            ast_stack.push(node)

    # Exit a parse tree produced by LittleParser#factor_prefix.
    def exitFactor_prefix(self, ctx: LittleParser.Factor_prefixContext):
        if ast_stack.peek().node_type == node_enum(
                6).name:  # if a placeholder node
            ast_stack.pop()
        else:
            mulop_node = ast_stack.pop()
            postfix_node = ast_stack.pop()
            fact_prefix_node = ast_stack.pop()

            if fact_prefix_node.node_type == node_enum(0).name:
                mulop_node.leftChild = postfix_node

            else:
                fact_prefix_node.rightChild = postfix_node
                mulop_node.leftChild = fact_prefix_node

            ast_stack.push(mulop_node)

    # Enter a parse tree produced by LittleParser#assign_expr.
    def enterAssign_expr(self, ctx: LittleParser.Assign_exprContext):
        # print(";Enter Assignment")
        var1 = ctx.getChild(0).getText()
        var2 = ctx.getChild(1).getText()
        var_type = ""
        currentScope = self.getCurrentScope()

        # get the type for id_node, first check if its in the current scope else get it from global scope
        if var1 in symbolTable[currentScope]:
            var_type = symbolTable[currentScope][var1][0]
        elif var1 in symbolTable['GLOBAL']:
            var_type = symbolTable['GLOBAL'][var1][0]

        # create varref node
        id_node = ASTNode(node_enum(3).name, var1, var_type)
        ast_stack.push(id_node)

        # create assexp node
        node = ASTNode(node_enum(4).name, var2)
        ast_stack.push(node)

    # Exit a parse tree produced by LittleParser#assign_expr.
    def exitAssign_expr(self, ctx: LittleParser.Assign_exprContext):
        exp_node = ast_stack.pop()
        assexp_node = ast_stack.pop()
        id_node = ast_stack.pop()

        assexp_node.rightChild = exp_node
        assexp_node.leftChild = id_node

        ast_stack.push(assexp_node)

    # Enter a parse tree produced by LittleParser#expr.
    def enterExpr(self, ctx: LittleParser.ExprContext):
        if ctx.getChild(0).getChildCount() == 0:
            ast_stack.push(ASTNode(node_enum(0).name, ""))  #push

    # Exit a parse tree produced by LittleParser#expr.
    def exitExpr(self, ctx: LittleParser.ExprContext):

        factor_node = ast_stack.pop()

        expr_prefix_node = ast_stack.pop()
        if expr_prefix_node.node_type == node_enum(0).name:
            ast_stack.push(factor_node)

        else:
            expr_prefix_node.rightChild = factor_node

            ast_stack.push(expr_prefix_node)

    # Enter a parse tree produced by LittleParser#postfix_expr.
    def enterPostfix_expr(self, ctx: LittleParser.Postfix_exprContext):
        pass

    # Exit a parse tree produced by LittleParser#postfix_expr.
    def exitPostfix_expr(self, ctx: LittleParser.Postfix_exprContext):
        pass

    # Enter a parse tree produced by LittleParser#read_stmt.
    def enterRead_stmt(self, ctx: LittleParser.Read_stmtContext):
        i = 0
        # A read node's values will be a list of tuples [(variable, type), (var, type)]
        node = ASTNode(node_enum(7).name, [], "")
        while i < ctx.getChild(2).getChildCount():
            var = ctx.getChild(2).getChild(i).getText()
            var = var.strip(",")
            var_type = ""
            currentScope = self.getCurrentScope()

            # get the type for node, first check if its in the current scope else get it from global scope
            if var in symbolTable[currentScope]:
                var_type = symbolTable[currentScope][var][0]
            elif var in symbolTable['GLOBAL']:
                var_type = symbolTable['GLOBAL'][var][0]

            if var != "":
                node.value.append((var, var_type))
            i += 1

        ast_stack.push(node)

    # Exit a parse tree produced by LittleParser#read_stmt.
    def exitRead_stmt(self, ctx: LittleParser.Read_stmtContext):
        pass

    # Enter a parse tree produced by LittleParser#write_stmt.
    def enterWrite_stmt(self, ctx: LittleParser.Write_stmtContext):
        currentScope = self.getCurrentScope()
        node = ASTNode(node_enum(8).name, [], "")
        i = 0
        while i < ctx.getChild(2).getChildCount():
            var = ctx.getChild(2).getChild(i).getText()
            var = var.split(",")
            if len(var) > 1:
                for v in var:
                    if (v != ""):
                        if v in symbolTable[currentScope]:
                            var_type = symbolTable[currentScope][v][0]
                        elif v in symbolTable['GLOBAL']:
                            var_type = symbolTable['GLOBAL'][v][0]
                        node.value.append((v, var_type))
            else:
                if (var[0] != ""):
                    # get the type for node, first check if its in the current scope else get it from global scope
                    if var[0] in symbolTable[currentScope]:
                        var_type = symbolTable[currentScope][var[0]][0]
                    elif var[0] in symbolTable['GLOBAL']:
                        var_type = symbolTable['GLOBAL'][var[0]][0]

                    node.value.append((var[0], var_type))
                    # statements_node.add("", node)
            i += 1

        ast_stack.push(node)

    # Exit a parse tree produced by LittleParser#write_stmt.
    def exitWrite_stmt(self, ctx: LittleParser.Write_stmtContext):
        pass

    # Enter a parse tree produced by LittleParser#return_stmt.
    def enterReturn_stmt(self, ctx: LittleParser.Return_stmtContext):
        pass

    # Exit a parse tree produced by LittleParser#return_stmt.
    def exitReturn_stmt(self, ctx: LittleParser.Return_stmtContext):
        pass

    # Enter a parse tree produced by LittleParser#primary.
    def enterPrimary(self, ctx: LittleParser.PrimaryContext):
        if ctx.getChildCount() > 1:
            pass
        else:
            var = ctx.getChild(0).getText()
            var_type = ""
            currentScope = self.getCurrentScope()

            # get the type for id_node, first check if its in the current scope else get it from global scope
            if var in symbolTable[currentScope]:
                var_type = symbolTable[currentScope][var][0]
            elif var in symbolTable['GLOBAL']:
                var_type = symbolTable['GLOBAL'][var][0]

            node = ASTNode(node_enum(3).name, var, var_type)

            ast_stack.push(node)

    # Exit a parse tree produced by LittleParser#primary.
    def exitPrimary(self, ctx: LittleParser.PrimaryContext):
        pass

    # Enter a parse tree produced by LittleParser#mulop.
    def enterMulop(self, ctx: LittleParser.MulopContext):
        node = ASTNode(node_enum(2).name, ctx.getChild(0).getText())
        ast_stack.push(node)

    # Exit a parse tree produced by LittleParser#mulop.
    def exitMulop(self, ctx: LittleParser.MulopContext):
        pass

    # Enter a parse tree produced by LittleParser#cond.
    def enterCond(self, ctx: LittleParser.CondContext):
        pass

    # Exit a parse tree produced by LittleParser#cond.
    def exitCond(self, ctx: LittleParser.CondContext):

        exp2 = ast_stack.pop()
        compop = ast_stack.pop()
        exp1 = ast_stack.pop()

        compop.rightChild = exp2
        compop.leftChild = exp1

        ast_stack.push(compop)

    # Enter a parse tree produced by LittleParser#compop.
    def enterCompop(self, ctx: LittleParser.CompopContext):

        # The label to jump to will be added in the exit while and exit if functions as the val_type
        node = ASTNode(node_enum(9).name, ctx.getText())
        ast_stack.push(node)

    # Exit a parse tree produced by LittleParser#compop.
    def exitCompop(self, ctx: LittleParser.CompopContext):
        pass

# Enter a parse tree produced by LittleParser#stmt_list.

    def enterStmt_list(self, ctx: LittleParser.Stmt_listContext):

        if ctx.getChildCount() == 0:
            node = ASTNode(node_enum(6).name, [])
            ast_stack.push(node)

    # Exit a parse tree produced by LittleParser#stmt_list.
    def exitStmt_list(self, ctx: LittleParser.Stmt_listContext):

        # If node is a Placeholder
        if ast_stack.peek().node_type == node_enum(6).name:
            ast_stack.pop()
            node = ASTNode(node_enum(5).name, [])
            ast_stack.push(node)

        # add a statement to the statement list and push back on to stack
        else:
            sl = ast_stack.pop()
            stmt = ast_stack.pop()

            sl.value.insert(0, stmt)

            ast_stack.push(sl)

    ################# UNNEEDED RULES #############################

    def enterDecl(self, ctx: LittleParser.DeclContext):
        pass

    # Exit a parse tree produced by LittleParser#decl.
    def exitDecl(self, ctx: LittleParser.DeclContext):
        pass

    # Enter a parse tree produced by LittleParser#st.
    def enterSt(self, ctx: LittleParser.StContext):
        pass

    # Exit a parse tree produced by LittleParser#st.
    def exitSt(self, ctx: LittleParser.StContext):
        pass

    # Enter a parse tree produced by LittleParser#var_type.
    def enterVar_type(self, ctx: LittleParser.Var_typeContext):
        pass

    # Exit a parse tree produced by LittleParser#var_type.
    def exitVar_type(self, ctx: LittleParser.Var_typeContext):
        pass

    # Enter a parse tree produced by LittleParser#any_type.
    def enterAny_type(self, ctx: LittleParser.Any_typeContext):
        pass

    # Exit a parse tree produced by LittleParser#any_type.
    def exitAny_type(self, ctx: LittleParser.Any_typeContext):
        pass

    # Enter a parse tree produced by LittleParser#func_declarations.
    def enterFunc_declarations(self,
                               ctx: LittleParser.Func_declarationsContext):
        pass

    # Exit a parse tree produced by LittleParser#func_declarations.
    def exitFunc_declarations(self,
                              ctx: LittleParser.Func_declarationsContext):
        pass

    # Enter a parse tree produced by LittleParser#func_body.
    def enterFunc_body(self, ctx: LittleParser.Func_bodyContext):
        pass

    # Exit a parse tree produced by LittleParser#func_body.
    def exitFunc_body(self, ctx: LittleParser.Func_bodyContext):
        pass

    # Enter a parse tree produced by LittleParser#stmt.
    def enterStmt(self, ctx: LittleParser.StmtContext):
        pass

    # Exit a parse tree produced by LittleParser#stmt.
    def exitStmt(self, ctx: LittleParser.StmtContext):
        pass

    # Enter a parse tree produced by LittleParser#base_stmt.
    def enterBase_stmt(self, ctx: LittleParser.Base_stmtContext):
        pass

    # Exit a parse tree produced by LittleParser#base_stmt.
    def exitBase_stmt(self, ctx: LittleParser.Base_stmtContext):
        pass

    # Enter a parse tree produced by LittleParser#pgm_body.
    def enterPgm_body(self, ctx: LittleParser.Pgm_bodyContext):
        pass

    # Exit a parse tree produced by LittleParser#pgm_body.
    def exitPgm_body(self, ctx: LittleParser.Pgm_bodyContext):
        pass

    # Enter a parse tree produced by LittleParser#im.
    def enterIm(self, ctx: LittleParser.ImContext):
        pass

    # Exit a parse tree produced by LittleParser#im.
    def exitIm(self, ctx: LittleParser.ImContext):
        pass
        # print("exit ID")

    # Enter a parse tree produced by LittleParser#expr_list_tail.
    def enterExpr_list_tail(self, ctx: LittleParser.Expr_list_tailContext):
        pass

    # Exit a parse tree produced by LittleParser#expr_list_tail.
    def exitExpr_list_tail(self, ctx: LittleParser.Expr_list_tailContext):
        pass

    # Enter a parse tree produced by LittleParser#call_expr.
    def enterCall_expr(self, ctx: LittleParser.Call_exprContext):
        pass

    # Exit a parse tree produced by LittleParser#call_expr.
    def exitCall_expr(self, ctx: LittleParser.Call_exprContext):
        pass

    # Enter a parse tree produced by LittleParser#id_list.
    def enterId_list(self, ctx: LittleParser.Id_listContext):
        #  print(ctx.getText())
        pass

    # Exit a parse tree produced by LittleParser#id_list.
    def exitId_list(self, ctx: LittleParser.Id_listContext):
        pass

    # Enter a parse tree produced by LittleParser#id_tail.
    def enterId_tail(self, ctx: LittleParser.Id_tailContext):
        pass

    # Exit a parse tree produced by LittleParser#id_tail.
    def exitId_tail(self, ctx: LittleParser.Id_tailContext):
        pass

    # Enter a parse tree produced by LittleParser#param_decl_list.
    def enterParam_decl_list(self, ctx: LittleParser.Param_decl_listContext):
        pass

    # Exit a parse tree produced by LittleParser#param_decl_list.
    def exitParam_decl_list(self, ctx: LittleParser.Param_decl_listContext):
        pass

    # Enter a parse tree produced by LittleParser#param_decl_tail.
    def enterParam_decl_tail(self, ctx: LittleParser.Param_decl_tailContext):
        pass

    # Exit a parse tree produced by LittleParser#param_decl_tail.
    def exitParam_decl_tail(self, ctx: LittleParser.Param_decl_tailContext):
        pass

    # Enter a parse tree produced by LittleParser#expr_list.
    def enterExpr_list(self, ctx: LittleParser.Expr_listContext):
        pass

    # Exit a parse tree produced by LittleParser#expr_list.
    def exitExpr_list(self, ctx: LittleParser.Expr_listContext):
        pass
Пример #30
0
 def create_new_stack(self, max_size=float("inf")):
     self.stacks.append(MyStack(max_size))
Пример #31
0
class MinStack(MyStack):
    def __init__(self):
        self.stack = MyStack()
        self.mins = MyStack()

    def isEmpty(self):
        return self.stack.isEmpty()

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

    def min(self):
        return self.mins.peek()

    def pop(self):
        self.mins.pop()
        return self.stack.pop()

    def push(self, item):
        current_min = self.min()
        if (current_min is None) or (item < current_min):
            self.mins.push(item)
        else:
            self.mins.push(current_min)

        self.stack.push(item)
Пример #32
0
	def setUp(self):
		print "=========== Running Stack Test ==========="
		self.s = MyStack()
Пример #33
0
class StacksOfPlates(MyStack):
    def __init__(self, threshold):
        self.threshold = threshold
        self.stacks = MyStack()
        self.lengths = MyStack()

    def isEmpty(self):
        return self.stacks.isEmpty()

    def peek(self):
        latest_stack = self.stacks.peek()
        if latest_stack is None:
            return None
        return latest_stack.peek()

    def pop(self):
        latest_stack = self.stacks.peek()
        if latest_stack is None:
            raise Error("Stack already empty. Underflow?")

        result = latest_stack.pop()

        if latest_stack.isEmpty():
            self.stacks.pop()
            self.lengths.pop()
        else:
            self.lengths.push(self.lengths.pop() - 1)

        return result

    def push(self, item):
        latest_length = self.lengths.peek()

        if (latest_length is None) or (latest_length == self.threshold):
            new_stack = MyStack()
            new_stack.push(item)
            self.stacks.push(new_stack)
            self.lengths.push(1)
        else:
            latest_stack = self.stacks.peek()
            latest_stack.push(item)
            self.lengths.push(self.lengths.pop() + 1)
Пример #34
0
def merge_sort(A):
    # if n == 1, done
    n = len(A)
    if n == 1:
        return A
    A1 = A[0:int(n/2)]
    A2 = A[int(n/2):]
    A1.sort()
    A2.sort()
    # "merge" the 2 sorted lists
    A1 = MyStack(A1)
    A2 = MyStack(A2)
    # 对于n个数字
    # B = []
    for i in range(n):
        a1 = A1.peek()
        a2 = A2.peek()
        if a1 == None:
            # 此时n次还没有执行完,所以a2一定不为空
            A[i] = a2
            # B.append(a2)
            A2.pop()
        elif a2 == None:
            # 此时n次还没有执行完,所以a1一定不为空
            A[i] = a1
            # B.append(a1)
            A1.pop()
        else:
            if a1 < a2:
                A[i] = a1
                # B.append(a1)
                A1.pop()
            else:
                A[i] = a2
                # B.append(a2)
                A2.pop()
    return A
Пример #35
0
 def __init__(self, threshold):
     self.threshold = threshold
     self.stacks = MyStack()
     self.lengths = MyStack()
Пример #36
0
def sort_stack(stack):
    sorter = MyStack()
    while not stack.isEmpty():
        holder = stack.pop()

        if sorter.isEmpty():
            sorter.push(holder)
        else:
            counter = 0
            while (not sorter.isEmpty()) and (sorter.peek() > holder):
                stack.push(sorter.pop())

            sorter.push(holder)

            for _ in range(counter):
                sorter.push(stack.pop())

    while not sorter.isEmpty():
        stack.push(sorter.pop())
def evaluate_postfix(postfix):
    s = MyStack()

    for i in postfix.split():
        if i == '+':
            s.push(s.pop() + s.pop())
        elif i == '-':
            expr2, expr1 = s.pop(), s.pop()
            s.push(expr1 - expr2)
        elif i == '*':
            s.push(s.pop() * s.pop())
        elif i == '/':
            expr2, expr1 = s.pop(), s.pop()
            s.push(expr1 // expr2)
        else:
            s.push(int(i))

    return s.pop()
Пример #38
0
class StacksOfPlates(MyStack):
    def __init__(self, threshold):
        self.threshold = threshold
        self.stacks = MyStack()
        self.lengths = MyStack()

    def isEmpty(self):
        return self.stacks.isEmpty()

    def peek(self):
        latest_stack = self.stacks.peek()
        if latest_stack is None:
            return None
        return latest_stack.peek()

    def pop(self):
        latest_stack = self.stacks.peek()
        if latest_stack is None:
            raise Error("Stack already empty. Underflow?")

        result = latest_stack.pop()

        if latest_stack.isEmpty():
            self.stacks.pop()
            self.lengths.pop()
        else:
            self.lengths.push(self.lengths.pop() - 1)

        return result

    def push(self, item):
        latest_length = self.lengths.peek()

        if (latest_length is None) or (latest_length == self.threshold):
            new_stack = MyStack()
            new_stack.push(item)
            self.stacks.push(new_stack)
            self.lengths.push(1)
        else:
            latest_stack = self.stacks.peek()
            latest_stack.push(item)
            self.lengths.push(self.lengths.pop() + 1)