class Test_myStack(unittest.TestCase): def setUp(self): self.testStack = MyStack() def test_pop_emptyStackCase(self): with self.assertRaises(StackEmptyException): self.testStack.pop() def test_pop_done(self): self.testStack.push('abc') self.testStack.push('xyz') self.testStack.push('123') self.testStack.pop() self.assertEqual(self.testStack.data, ['abc', 'xyz']) def test_peek(self): with self.assertRaises(StackEmptyException): self.testStack.peek() def test_push_typeErrorCase(self): with self.assertRaises(TypeError): self.testStack.push(10) def test_push_done(self): self.testStack.push('abc') self.testStack.push('xyz') self.testStack.push('123') self.testStack.push('456') self.assertEqual(self.testStack.data, ['abc', 'xyz', '123', '456']) def test_contain(self): self.testStack.push('abc') self.assertTrue(self.testStack.contains('abc'), 'Must be True')
def next_greater_element(lst): stack = MyStack() res = [None] * len(lst) for i in range(len(lst) - 1, -1, -1): # iterate backwards while not stack.is_empty() and stack.peek() <= lst[i]: stack.pop() if not stack.is_empty(): # use the top element as nge if available res[i] = stack.peek() else: res[i] = -1 stack.push(lst[i]) return res
def sort_stack(stack): temp_stack = MyStack() while not stack.is_empty(): value = stack.pop() # if value is not none and larger, push it at the top of temp_stack if temp_stack.peek() is not None and value >= temp_stack.peek(): temp_stack.push(value) else: while not temp_stack.is_empty(): stack.push(temp_stack.pop()) # place value as the smallest element in temp_stack temp_stack.push(value) # Transfer from temp_stack => stack while not temp_stack.is_empty(): stack.push(temp_stack.pop()) return stack