Exemplo n.º 1
0
def build_parse_tree(expression):
    if not expression:
        return None

    expression = list(expression.replace(' ', ''))
    curr_node = TreeNode()
    stack = Stack()
    stack.push(curr_node)

    for token in expression:
        if token == '(':
            curr_node.left = TreeNode()
            stack.push(curr_node)
            curr_node = curr_node.left

        elif token in operators:
            curr_node.data = token
            curr_node.right = TreeNode()
            stack.push(curr_node)
            curr_node = curr_node.right

        elif token == ')':
            curr_node = stack.pop()

        else:
            # if token is an operand
            curr_node.data = token
            curr_node = stack.pop()

    return curr_node
Exemplo n.º 2
0
def sort_stack(orig):
    if not orig or not isinstance(orig, Stack):
        return None

    dup = Stack()

    while not orig.is_empty():
        item = orig.pop()

        if dup.is_empty():
            dup.push(item)

        elif item >= dup.peek():
            dup.push(item)

        else:
            while item < dup.peek():
                orig.push(dup.pop())

            orig.push(item)

            while not dup.is_empty():
                orig.push(dup.pop())

    while not dup.is_empty():
        orig.push(dup.pop())
Exemplo n.º 3
0
def build_parse_tree(expression):
    if not expression:
        return None

    expression = list(expression.replace(' ', ''))
    curr_node = TreeNode()
    stack = Stack()
    stack.push(curr_node)

    for token in expression:
        if token == '(':
            curr_node.left = TreeNode()
            stack.push(curr_node)
            curr_node = curr_node.left

        elif token in operators:
            curr_node.data = token
            curr_node.right = TreeNode()
            stack.push(curr_node)
            curr_node = curr_node.right

        elif token == ')':
            curr_node = stack.pop()

        else:
            # if token is an operand
            curr_node.data = token
            curr_node = stack.pop()

    return curr_node
Exemplo n.º 4
0
def sort_stack(orig):
    if not orig or not isinstance(orig, Stack):
        return None

    dup = Stack()

    while not orig.is_empty():
        item = orig.pop()

        if dup.is_empty():
            dup.push(item)

        elif item >= dup.peek():
            dup.push(item)

        else:
            while item < dup.peek():
                orig.push(dup.pop())

            orig.push(item)

            while not dup.is_empty():
                orig.push(dup.pop())


    while not dup.is_empty():
        orig.push(dup.pop())
Exemplo n.º 5
0
def infix_to_postfix(s):
    if not s:
        raise ValueError('input cannot be None or empty string')

    seq = s.split()
    out = []
    st = Stack()

    for c in seq:
        if c in operators:
            while not st.is_empty() and precedence[c] <= precedence[st.peek()]:
                out.append(st.pop())
            st.push(c)

        elif c == '(':
            st.push(c)

        elif c == ')':
            while not st.is_empty():
                item = st.pop()
                if item == '(': break
                else: out.append(item)

        else:
            out.append(c)

    while not st.is_empty():
        out.append(st.pop())

    return ' '.join(out)
Exemplo n.º 6
0
def is_balanced_simple_parantheses(s):
    if not s: return True

    stack = Stack()
    for c in s:
        if c == '(':
            stack.push(c)
        if c == ')':
            if stack.is_empty(): return False
            else: stack.pop()

    return stack.is_empty()
Exemplo n.º 7
0
def is_balanced_simple_parantheses(s):
    if not s: return True

    stack = Stack()
    for c in s:
        if c == '(':
            stack.push(c)
        if c == ')':
            if stack.is_empty(): return False
            else: stack.pop()

    return stack.is_empty()
Exemplo n.º 8
0
class TestStackStructure(unittest.TestCase):
    '''
    Test for:
    1. instantiating the Stack worked
    2. is_empty() works
    3. size() works
    4. push:
	- does not push None values
        - check size() when item is pushed
    5. pop:
	- does nothing when stack is empty
	- pops item in lifo manner
    6. peek:
	- push an item and check if peek() gives us the same item
    '''
    def setUp(self):
        self.seq = range(5)
        self.stack = Stack()

    def test_stack_creation(self):
        self.assertIsInstance(self.stack, Stack)

    def test_is_empty(self):
        self.assertTrue(self.stack.is_empty())

    def test_empty_stack_size_is_zero(self):
        self.assertEqual(self.stack.size(), 0)

    def test_push_method(self):
        self.stack.push(None)
        self.assertEqual(self.stack.size(), 0)
        self.stack.push([])
        self.assertEqual(self.stack.size(), 1)

    def test_peek_method(self):
        self.assertEqual(self.stack.peek(), None)
        self.stack.push(5)
        self.stack.push(6)
        self.assertEqual(self.stack.peek(), 6)

    def test_pop_method(self):
        self.assertEqual(self.stack.pop(), None)
        for i in self.seq:
            self.stack.push(i)

        for i in reversed(self.seq):
            self.assertEqual(self.stack.pop(), i)
Exemplo n.º 9
0
def eval_postfix(s):
    if not s:
        raise ValueError('input cannot be None of empty string')

    seq = s.split()
    st = Stack()

    for c in seq:
        if c not in operators:
            print 'pushing', c
            st.push(c)
        else:
            op2 = st.pop()
            op1 = st.pop()

            result = evaluate(op1, op2, c)
            st.push(result)

    return st.pop()
Exemplo n.º 10
0
def reverse_using_stack(s):
    if not s: return s

    stack = Stack()
    for c in s:
        stack.push(c)

    new_s = ''
    while not stack.is_empty():
        new_s += stack.pop()

    return new_s
Exemplo n.º 11
0
def reverse_using_stack(s):
    if not s: return s

    stack = Stack()
    for c in s:
        stack.push(c)

    new_s = ''
    while not stack.is_empty():
        new_s += stack.pop()

    return new_s
Exemplo n.º 12
0
def is_balanced_all_parantheses(s):
    if not s: return True

    stack = Stack()
    for c in s:
        if c in '([{':
            stack.push(c)
        if c in ')]}':
            if stack.is_empty(): return False
            top = stack.pop()
            if matches[top] != c: return False

    return stack.is_empty()
Exemplo n.º 13
0
def dec_to_bin(n):
    if not isinstance(n, (int, long)): raise Exception('Not an int value')

    st = Stack()
    while n != 0:
        st.push(n % 2)
        n = n/2

    b = ''
    while not st.is_empty():
        b += str(st.pop())

    return b
Exemplo n.º 14
0
def dec_to_bin(n):
    if not isinstance(n, (int, long)): raise Exception('Not an int value')

    st = Stack()
    while n != 0:
        st.push(n % 2)
        n = n / 2

    b = ''
    while not st.is_empty():
        b += str(st.pop())

    return b
Exemplo n.º 15
0
def is_balanced_all_parantheses(s):
    if not s: return True

    stack = Stack()
    for c in s:
        if c in '([{':
            stack.push(c)
        if c in ')]}':
            if stack.is_empty(): return False
            top = stack.pop()
            if matches[top] != c: return False

    return stack.is_empty()
Exemplo n.º 16
0
def base_convertor(decimal_num, base):
    if not isinstance(decimal_num, (int, long)): raise Exception('input must be a valid integer')

    if not isinstance(base, (int, long)) or base < 2 or base > 16: raise Exception('invalid base value')

    if decimal_num < 0: raise Exception('handling only positive numbers right now')

    st = Stack()
    while decimal_num != 0:
        rem = decimal_num % base
        st.push( get_mod_value(rem, base) )
        decimal_num /= base

    b = ''
    while not st.is_empty():
        b += st.pop()

    return b
Exemplo n.º 17
0
def dfs_traversal(tree_node):
    if not tree_node: return []

    stack = Stack()
    stack.push(tree_node)
    result = []

    while not stack.is_empty():
        item = stack.pop()
        result.append(item.data)

        if item.right:
            stack.push(item.right)

        if item.left:
            stack.push(item.left)

    return result
Exemplo n.º 18
0
def base_convertor(decimal_num, base):
    if not isinstance(decimal_num, (int, long)):
        raise Exception('input must be a valid integer')

    if not isinstance(base, (int, long)) or base < 2 or base > 16:
        raise Exception('invalid base value')

    if decimal_num < 0:
        raise Exception('handling only positive numbers right now')

    st = Stack()
    while decimal_num != 0:
        rem = decimal_num % base
        st.push(get_mod_value(rem, base))
        decimal_num /= base

    b = ''
    while not st.is_empty():
        b += st.pop()

    return b