示例#1
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)
示例#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())
示例#3
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())
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()
示例#5
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
示例#6
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
示例#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()
示例#8
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
示例#9
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
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()
示例#11
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()
示例#12
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
示例#13
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()
示例#14
0
def test():
    s = Stack()
    s.push(44)
    s.push(32)
    s.push(39)
    s.push(-22)
    s.push(14)

    print s.data

    sort_stack(s)

    print s.data
示例#15
0
def test():
    s = Stack()
    s.push(44)
    s.push(32)
    s.push(39)
    s.push(-22)
    s.push(14)

    print s.data

    sort_stack(s)

    print s.data
示例#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
示例#17
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
示例#18
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
示例#19
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)
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
示例#21
0
from data_structures.stacks import Stack
from math import sqrt

stack = Stack(6)
stack.push("Python")
stack.push(1)
stack.push(5)
stack.push(dict(brian="Brian", lusina="Lusina", ombito="Ombito"))
stack.push((1, 5))
stack.push(range(5))

stack.display()

print(stack.filter_stack())

print(stack.filter_stack()[int])

示例#22
0
def move_disks(no_of_disks, from_stack, to_stack, using_stack):
    if no_of_disks == 0: return

    move_disks(no_of_disks - 1, from_stack, using_stack, to_stack)
    move_disk(from_stack, to_stack)
    move_disks(no_of_disks - 1, using_stack, to_stack, from_stack)



if __name__ == '__main__':
    no_of_disks = 4

    stackA = Stack()
    for i in reversed(range(no_of_disks)):
        stackA.push(i * 2)

    stackB = Stack()
    stackC = Stack()

    print 'A:', stackA
    print 'B:', stackB
    print 'C:', stackC

    move_disks(no_of_disks, stackA, stackC, stackB)
    print 

    print 'A:', stackA
    print 'B:', stackB
    print 'C:', stackC
示例#23
0

def move_disks(no_of_disks, from_stack, to_stack, using_stack):
    if no_of_disks == 0: return

    move_disks(no_of_disks - 1, from_stack, using_stack, to_stack)
    move_disk(from_stack, to_stack)
    move_disks(no_of_disks - 1, using_stack, to_stack, from_stack)


if __name__ == '__main__':
    no_of_disks = 4

    stackA = Stack()
    for i in reversed(range(no_of_disks)):
        stackA.push(i * 2)

    stackB = Stack()
    stackC = Stack()

    print 'A:', stackA
    print 'B:', stackB
    print 'C:', stackC

    move_disks(no_of_disks, stackA, stackC, stackB)
    print

    print 'A:', stackA
    print 'B:', stackB
    print 'C:', stackC