def is_balanced(string): stack = Stack("Brackets") for ch in string: if ch in ["(", "{", "["]: stack.push(ch) else: if ch == ")" and not stack.empty() and stack.peek() == "(": stack.pop() if ch == "}" and not stack.empty() and stack.peek() == "{": stack.pop() if ch == "]" and not stack.empty() and stack.peek() == "[": stack.pop() return False if stack else True
def test_new_stack_is_empty(self): """ Create an empty Stack. Test that its size is 0. """ stack = Stack() self.assertTrue(stack.empty()) self.assertEqual(stack.size(), 0)
def test_push_element(self): """ Push an element in stack. Test that its size is 1. """ stack = Stack() stack.push(None) self.assertFalse(stack.empty()) self.assertEqual(stack.size(), 1)
def test_new_stack_from_generator(self): """ Create a Stack from a generator. Test that its size equals to the number provided in the generator. """ stack = Stack(range(10)) self.assertFalse(stack.empty()) self.assertEqual(stack.size(), 10) self.assertEqual(stack.top(), 9)
def test_new_stack_from_list(self): """ Create a Stack from a list. Check that the size of stack equals to the size of the list. Check that the top element of stack equals to the latest element of the list. """ data_to_stack = (1, 3, 5, 7, 2, 4) stack = Stack(data_to_stack) self.assertFalse(stack.empty()) self.assertEqual(stack.size(), len(data_to_stack)) self.assertEqual(stack.top(), data_to_stack[-1])
def test_push_sequence_of_elements(self): """ Push a sequence of elements in stack. Test that its size equals to the length of the given sequence. Pop all elements from stack and check reversed order. """ stack = Stack() elements = (1, 2, "string", None, 0, Stack()) map(stack.push, elements) self.assertEqual(stack.size(), len(elements)) for index, element in enumerate(reversed(elements)): top = stack.top() self.assertEqual(top, element) stack.pop() number_pop_elements = index + 1 expected_current_stack_size = len(elements) - number_pop_elements self.assertEqual(stack.size(), expected_current_stack_size) self.assertTrue(stack.empty())
def test_stack_not_empty_after_push(self): stack = Stack() stack.push(0) assert not stack.empty()
def test_initialized_stack_is_empty(self): stack = Stack() assert stack.empty()