def test_pop(self): s = Stack(['A', 'B', 'C']) assert s.pop() == 'C' assert s.length() == 2 assert s.pop() == 'B' assert s.length() == 1 assert s.pop() == 'A' assert s.length() == 0 assert s.is_empty() is True with self.assertRaises(ValueError): s.pop()
def test_length(self): s = Stack() assert s.length() == 0 s.push('A') assert s.length() == 1 s.push('B') assert s.length() == 2 s.pop() assert s.length() == 1 s.pop() assert s.length() == 0
def test_push(self): s = Stack() s.push('A') assert s.peek() == 'A' assert s.length() == 1 s.push('B') assert s.peek() == 'B' assert s.length() == 2 s.push('C') assert s.peek() == 'C' assert s.length() == 3 assert s.is_empty() is False
def reverse(nums): #declare your stack Stack = LinkedStack() #init the stack #declare a variable to get track of the reversed number reversed = [] #add each number in nums to the stack for num in nums: # Loop through the whole list O(n) if num == '-': reversed.append(num) #adds sign to list O(1) if num.isdigit(): Stack.push(num) #adds num to stack O(1) #traverse through the stack while Stack.length() > 0: # Loops through the whole stack #add the head of the stack then delete the head reversed.append(Stack.peek()) # adds number back to list O(1) Stack.pop() # deletes current stack to move to the next one O(1) if reversed[0] == '-': if reversed[1] == '0': reversed.pop(1) #removes a digit O(1) if reversed[0] == '0': reversed.pop(0) #removes a digit O(1) return "".join(reversed)
def _traverse_in_order_iterative(self, node, visit): """Traverse this binary tree with iterative in-order traversal (DFS). Start at the given node and visit each node with the given function. Running time: O(n) since we visit every node Memory usage: O(logn) for the depth of the tree""" # -create an empty stack # -curr variable which starts off with the self.root (will be updated in a while loop!!) # -go in a while loop while true (will be false when the stack is empty) # -call push() on curr while there's a value # -update the curr to become the curr's left # -once we hit a None value: # - we'd want to pop() off the stack # - append it to the list # - update curr to be the recently popped node's right node # - however, if the stack is empty in here, we set the while loop to false and exit the function! stack = LinkedStack() # will act as the recursive call curr = self.root # start at the root stillLoop = True # loop until the stack is empty while stillLoop: # we're at the end of a leaf node if curr == None: if stack.length() > 0: node = stack.pop() visit(node.data) curr = node.right # our stack is empty so we can finally return once all the nodes have been visited else: stillLoop = False # we can still go down the left side else: stack.push(curr) curr = curr.left
def test_init(self): s = Stack() assert s.peek() is None assert s.length() == 0 assert s.is_empty() is True
def test_init_with_list(self): s = Stack(['A', 'B', 'C']) assert s.peek() == 'C' assert s.length() == 3 assert s.is_empty() is False