def parenthesesChecker(string): """ Parentheses Checker validates the string using stack INPUT --------- string : '(()))' RETURN --------- Flag : False """ temp = Stack(); balanceFlag = False for i in string: if i == "(": temp.push('i') if i == ")": if temp.isEmpty(): balanceFlag = False else: temp.pop(); balanceFlag = True if balanceFlag and temp.isEmpty(): return True else: return False
def test_isEmpty(self): stack_empty = Stack() stack_full = Stack() stack_full.push('test') self.assertEqual(stack_empty.isEmpty(), True) self.assertEquals(stack_full.isEmpty(), False)
def toStr(n, base): """ Convert given number to number in different base Instead of concatenating the result of the recursive call to toStr with the string from stringMap, Push the strings onto a stack instead of making the recursive call INPUT ------- n : Input number eg 1453 base : base to convert the number to eg. 16 or Hexadecimal RETURN ------- newStr = (1453,16) => 5AD """ tempStack = Stack() stringMap = '0123456789ABCDEF' newStr = '' while (n > 0): quotient = n // base remainder = n % base if remainder > 9: tempStack.push(stringMap[remainder]) else: tempStack.push(remainder) n = n // base while not tempStack.isEmpty(): newStr += str(tempStack.pop()) return newStr
def rev_string(test_str): string_stack = Stack() for ch in test_str: string_stack.push(ch) reverse_string = '' while not string_stack.isEmpty(): reverse_string = reverse_string + string_stack.pop() return reverse_string
def testStack(self): stack = Stack() self.assertTrue(stack.isEmpty()) stack.push(5) self.assertFalse(stack.isEmpty()) stack.clear() self.assertTrue(stack.isEmpty()) stack.push(6) self.assertEqual(6, stack.top()) self.assertEqual(6, stack.pop()) self.assertTrue(stack.isEmpty()) stack.push(7) stack.push(6) stack.push(5) self.assertEqual(5, stack.pop()) self.assertEqual(6, stack.pop()) self.assertEqual(7, stack.top())
def divide_by_2(dec_num): remstack = Stack() while dec_num > 0: rem = dec_num % 2 remstack.push(rem) dec_num = dec_num // 2 bin_string = "" while not remstack.isEmpty(): bin_string = bin_string + str(remstack.pop()) return bin_string
def isBallanced(str): open = '(', '[', '{' close = ')', ']', '}' st = Stack() for ch in str: if ch in open: st.push(ch) elif ch in close: if st.isEmpty(): return False idxClose = close.index(ch) op = st.pop() idxOpen = open.index(op) if idxClose != idxOpen: return False if not st.isEmpty(): return False return True