def test_pop_one_item(self):
     value1 = 5
     my_stack = Stack()
     my_stack.push(value1)
     popped_item = my_stack.pop()
     self.assertEqual(5, popped_item)
     self.assertEqual(0, my_stack.count)
 def test_peek_single_item(self):
     value1 = 5
     my_stack = Stack()
     my_stack.push(value1)
     peeked_item = my_stack.peek()
     self.assertEqual(1, my_stack.count)
     self.assertEqual(5, peeked_item)
def build_parse_tree(p_exression):
    char_list = p_expression.split()
    s = Stack()
    current_node = BinaryTree('')
    s.push(current_node)

    for char in char_list:
        if char == '(':
            current_node.insert_left('')
            s.push(current_node)
            current_node = current_node.get_left_child()

        # for numeric values
        elif char not in "()+-*/%":
            current_node.set_root_val(int(char))
            current_node = s.pop()

        # for operators
        elif char in "+-*/%":
            current_node.set_root_val(char)
            current_node.insert_right('')
            s.push(current_node)
            current_node = current_node.get_right_child()

        # if ')', then make the parent te current node (till there's no parent and the tree is thus complete)
        elif char == ')':
            current_node = s.pop()

        else:
            raise ValueError

        return current_node
def eval(list):   
    op = Stack()
    val = Stack()

    for i in list:
        if type(i)== int:
            val.push(int(val))
示例#5
0
def buildParseTree(math_exp):
    mlist = math_exp.split()
    pStack = Stack()
    aTree = BinaryTree('')
    pStack.push(aTree)
    currentTree = aTree

    for num in mlist:
        # When we see open bracket, make a left child node since number will go there
        if num == '(':
            currentTree.insertLeft('')
            pStack.push(currentTree)
            currentTree = currentTree.getLeftChild()

        # if it is operator, we set that parent to be the operator then make a right child
        elif num in ['+', '-', '*', '/']:
            currentTree.setRootVal(num)
            currentTree.insertRight('')
            pStack.push(currentTree)
            currentTree = currentTree.getRightChild()
        # closing the bracket so go back to the parent of the operator node
        elif num == ')':
            currentTree = pStack.pop()

        # this is presume to be a number, want to set the current node to that number, then go back to the parent
        elif num not in ['+', '-', '*', '/', ')']:
            try:
                currentTree.setRootVal(int(num))
                parent = pStack.pop()
                currentTree = parent

            except ValueError:
                raise ValueError(num, "is not a valid integer")
    return aTree
def build_parse(data):
    data = list(data)
    ops = Stack()
    tree = BinaryTree(" ")
    curr = tree
    print curr
    ops.push(tree)
    for i in data:
        if i == "(":
            curr.insert_left(" ")
            ops.push(curr)
            curr = curr.get_left()
        elif i not in '+-*/)':
            curr.set_root(int(i))
            curr = ops.pop()
        elif i in '+-*/':
            curr.set_root(i)
            curr.insert_right(" ")
            ops.push(curr)
            curr = curr.get_right()
        elif i == ')':
            curr = ops.pop()
        else:
            raise ValueError("unsupported operator " + i)
    return tree
 def __init__(self, width, height):
     self.nodeList = []
     self.width = width
     self.height = height
     self.grid = None
     self.nodeStack = Stack()
     self.fRows = 0
     self.fCols = 0
示例#8
0
 def __init__(self, width, height):
     '''width and height are the minimum distance between nodes'''
     self.nodeList = []
     self.width = width
     self.height = height
     self.grid = None
     self.nodeStack = Stack()
     self.fRows = 0
     self.fCols = 0
示例#9
0
 def __init__(self, level):
     self.level = level
     self.nodeList = []
     self.grid = None
     self.nodeStack = Stack()
     self.nodeSymbols = ["+", "n", "N", "M", "H", "F"]
     self.homeList = []
     self.createMainList()
     self.createHomeList()
示例#10
0
 def __init__(self, level):
     self.level = level
     self.nodeList = []
     self.grid = None
     self.nodeStack = Stack()
     #self.createNodeList(MAZEDATA[level]["file"], self.nodeList)
     self.homeList = []
     self.nodeSymbols = ["+", "n", "N", "M", "H", "F"]
     self.createMainList()
     self.createHomeList()
示例#11
0
def rpn_calc(postfix_expr: str):
    '''Evaluate a postfix expression'''
    operand_stack = Stack()
    token_list = postfix_expr.split()

    print(postfix_expr)
    print(token_list)

    try:
        for ind in range(len(token_list)):
            if token_list[ind] in "0123456789":
                # Seperates the operands in a Stack
                operand_stack.push(int(token_list[ind]))
            else:
                # Does calculations with the operands
                operand2 = operand_stack.pop()
                operand1 = operand_stack.pop()
                result = do_math(token_list[ind], operand1, operand2)

                # If the Stack still has elements
                if ind == len(token_list) - 1 and not operand_stack.is_empty():
                    raise StackError(
                        "Unknown expression {}".format(postfix_expr))
                else:
                    operand_stack.push(result)
                    return (operand_stack.pop())
    except IndexError:
        raise StackError("Stack is empty")
示例#12
0
def decimalToBinaryConverter(decimal_number):
    if not isinstance(decimal_number, int): 
        raise Exception('Invalid object provided for conversion, valid datatype in INT')
    
    bin_stack = Stack()
    quotient = decimal_number
    remainder = None
    while quotient > 0:
        remainder = int(quotient % 2)
        quotient = int(quotient / 2)
        bin_stack.push(remainder)
    return str(bin_stack)
def reverse_string(string):
    """Return a string backwards."""
    s = Stack()
    reverse_text = ''
    for char in string:
        s.push(char)

    s.container.reverse()
    for i in s.container:
        reverse_text += i

    print(reverse_text)
示例#14
0
 def shuffle(self, cut=26, skill=1):
     left = Stack(self.deck[:cut:-1])
     right = Stack(self.deck[cut::-1])
     shuffled = []
     if not isinstance(skill, int) or skill < 0 or skill > 1:
         raise CardError("Invalid input: check the skill parameters!")
     if not isinstance(cut, int) or cut < 0 or cut > 52:
         raise CardError("Invalid input: check the cut parameters!")
     if skill == 1:
         constant = True
     if skill != 1:
         percentage_error = 1 - skill
         possible_error = int(min(left, right) * percentage_error)
         possibilities = range(1, possible_error + 2)
     while left.stack and right.stack:
         if not constant:
             try:
                 shuffled.append(right.pop(choice(possibilities)))
             except:
                 shuffled.extend(right)
             try:
                 shuffled.append(left.pop(choice(possibilities)))
             except:
                 shuffled.extend(left)
         else:
             shuffled.append(right.pop())
             shuffled.append(left.pop())
     shuffled.extend(left)
     shuffled.extend(right)
     self.deck = shuffled
     return self.deck
示例#15
0
    def __init__(self, screen, level):
        self.settings = Settings()
        self.screen = screen
        self.level = level

        self.type_of_node = ["+", "n", "N", "o"]
        self.ghost_node = ["v"]
        self.type_of_path = ["p", "P"]

        self.nodeList = []
        self.ghostList = []

        self.grid = None
        self.nodeStack = Stack()
        self.create_node_list()
示例#16
0
def test_push_onto_full():
    s = Stack()
    s.push("apple")
    s.push("banana")
    s.push("cucumber")
    actual = s.top_of_list.value
    expected = "cucumber"
    assert actual == expected
示例#17
0
    def depth_first_traversal(self, start):
        depth_list = []
        new_stack = Stack([start])
        while True:
            try:
                node = new_stack.pop()
                if node not in depth_list:
                    depth_list.append(node)
                    children = list(self.dict[node].keys())

                    for child in children:
                        new_stack.push(child)

            except AttributeError:
                return depth_list
示例#18
0
    def depth_first_traversal(self, start):
        depth_list = []
        new_stack = Stack([start])
        while True:
            try:
                node = new_stack.pop()
                if node not in depth_list:
                    depth_list.append(node)
                    children = list(self.dict[node].keys())

                    for child in children:
                        new_stack.push(child)

            except AttributeError:
                return depth_list
class QueueFromStack:
    def __init__(self):
        self.in_storage = Stack()
        self.out_storage = Stack()

    def size(self):
        return self.in_storage.size() + self.out_storage.size()

    def enqueue(self, value):
        self.in_storage.push(value)

    def dequeue(self):
        if self.out_storage.size() == 0:
            while self.in_storage.size() != 0:
                self.out_storage.push(self.in_storage.pop())
        return self.out_storage.pop()
示例#20
0
def test_sort_stack():
    a = get_random_list(5)
    stack = Stack()
    for x in a:
        stack.push(x)

    stack.print_stack()
    sort_stack(stack)
    stack.print_stack()
示例#21
0
 def preorder(self, start):
     stack = Stack()
     current = start
     visited = False
     traversal = ""
     while not visited:
         if current is not None:
             traversal += str(current.data) + " "
             stack.push(current.data)
             current = current.left
         else:
             if len(stack) > 0:
                 current = stack.pop()
                 current = current.right
             else:
                 visited = True
     return traversal
示例#22
0
 def __init__(self, level):
     self.nodelist = []
     self.homelist = []
     self.level = level
     # self.grid = None
     self.node_stack = Stack()
     self.portalSymbols = ["z"]
     self.pathSymbols = ["p", "P"]
     self.nodeSymbols = ["+", "n", "N", "H", "S", "Y", "F"
                         ] + self.portalSymbols
     self.grid = self.read_maze_file(level)
     self.homegrid = self.get_home_array()
     self.create_node_list(self.grid, self.nodelist)
     self.create_node_list(self.homegrid, self.homelist)
     self.setup_portal_nodes()
     self.move_home_nodes()
     self.homelist[0].is_ghost_start = True
示例#23
0
 def test_pop_in_correct_order_from_2_item_stack(self):
     test_obj = Stack()
     test_data1 = 'data1'
     test_data2 = 'data2'
     test_obj.push(test_data1)
     test_obj.push(test_data2)
     self.assertEqual(test_data2, test_obj.pop())
     self.assertEqual(False, test_obj.is_empty())
     self.assertEqual(test_data1, test_obj.pop())
     self.assertEqual(True, test_obj.is_empty())
示例#24
0
def test_check_not_empty():
    s = Stack()
    s.push("apple")
    s.push("banana")
    actual = s.is_empty()
    expected = False
    assert actual == expected
示例#25
0
def test_peek():
    s = Stack()
    s.push("apple")
    s.push("banana")
    actual = s.peek()
    expected = "banana"
    assert actual == expected
示例#26
0
class MaxStack:

    def __init__(self):
        self.stack = Stack()
        self.largest = Stack()
    
    def push(self, item):
        self.stack.push(item)
        if item >= self.largest.peek():
            self.largest.push(item)

    def pop(self):
        item = self.stack.pop()
        if item == self.largest.peek():
            self.largest.pop()
        return item

    def get_largest(self):
        return self.largest.peek()
示例#27
0
def deciToBin(num):
    binaryStack = Stack()
    binNum = ""
    print(f"The binary of {num} is: ", end="")
    while num > 0:
        binaryStack.push(num % 2)
        num = num // 2

    while not (binaryStack.isEmpty()):
        binNum += str(binaryStack.peek())
        binaryStack.pop()
    print(binNum)
示例#28
0
def abs_to_relative_two(s):
    stack = Stack()
    index = 0
    len_f = len(s)
    while index < len_f:
        while index< len_f and s[index] != '.':
            stack.push(s[index])
            index += 1
        point_count = 0
        while index<len_f and s[index] == '.':
            index += 1
            point_count += 1
        if point_count == 2:
            stack.pop()
            while not stack.isEmpty() and stack.peer() != '/':
                stack.pop()

        index += 1
    return ''.join(stack.items) # print relative path
示例#29
0
class Deck:
    "A bilota deck of cards."

    def __init__(self):
        self.cards = Stack()
        for s in suits:
            for r in ranks:
                self.cards.push(Card(r, s))

    def shuffle(self):
        """Shuffles the Deck only if it has max size."""
        if self.cards.size() == 32:
            shuffle(self.cards.items)

        raise RuntimeError('Only a full Deck can be shuffled.')

    def get_card(self):
        """Gets a card from the Deck."""
        return self.cards.pop()
示例#30
0
def searchDFSTrace(graph, start, end):
    stack = Stack()
    stack.push([start])
    while not stack.isEmpty():
        path = stack.pop()
        last = path[-1]
        if last == end:
            return path
        for adjacent in graph.get(last, []):
            new_path = list(path)
            new_path.append(adjacent)
            stack.push(new_path)
示例#31
0
def searchDFS(graph, start):
    visited = []
    stack = Stack()
    stack.push(start)
    while not stack.isEmpty():
        vertex = stack.pop()
        if vertex not in visited:
            visited.append(vertex)
            print 'VERTEX', vertex
            for edges in graph[vertex]:
                stack.push(edges)
    return visited
示例#32
0
 def __init__(self, name, nr_containers):
     #print("port created")
     self.ship_queue = []
     self.docks = []
     self.ne_stacks = []
     self.name = name
     self.nr_docks = 7
     self.nr_non_empty_stacks = 16
     self.max_capacity = 3000
     for i in range(self.nr_docks):
         self.docks.append(Dock(i))
     for i in range(8):
         self.ne_stacks.append(Stack(str(str(i)), "non empty", i, 0))
     for i in range(8, 16):
         self.ne_stacks.append(Stack(str(str(i)), "non empty", i - 8, 1))
     self.e_stack = Stack(str("E"), "empty", 0, 0)
     self.nr_containers = nr_containers
     self.date = 0
     self.emptyC = 20
def check_balanced_brackets(bracket_str):
    bracket_list = list(bracket_str)
    bracket_stack = Stack()
    for symbol in bracket_list:
        if symbol in ['(', '{', '[']:
            bracket_stack.push(symbol)
            continue
        elif symbol in [')', '}', ']']:
            if not bracket_stack.is_empty() and pair_match(
                    symbol, bracket_stack.peak()):
                bracket_stack.pop()
            else:
                return False
        else:
            raise Exception('Invalid symbol found')
    return bracket_stack.is_empty()
def htmlChecker(html):
    stk = Stack()
    intag = False

    for index in xrange(len(html)):
        """Loops over html doc searching for tags
            when an opening bracket is found the
            tag is pushed onto the stack"""
        if html[index] == '<':
            intag = True
            count = index
            while intag:
                stk.push(html[count])
                if html[count] == '>':
                    intag = False
                else:
                    count = count + 1
                    
    for index in xrange(len(html)):
        """Loops again over html doc but when
            tag is found it compares to popped item"""
        if html[index] == '<':
            intag = True
            count = index
            while intag:
                if len(stk) <= 0:
                    return True
                else:
                    item = stk.pop()
                    if html[count] == '>':
                        intag = False
                    elif html[count] == '/' or item != '/':   
                        None
                    elif html[count] != '/' and item != '/':
                        if html[count] == '<' and item == '>'\
                           or html[count] == '>' and item == '<':
                            count = count + 1
                        elif html[count] == item:
                            count = count + 1
                        else:
                            print count
                            return False
示例#35
0
def searchDFSTrace(graph, start, end):
    stack = Stack()
    stack.push([start])
    while not stack.isEmpty():
        path = stack.pop()
        last = path[-1]
        if last == end:
            return path
        for adjacent in graph.get(last, []):
            new_path = list(path)
            new_path.append(adjacent)
            stack.push(new_path)
示例#36
0
def searchDFS(graph, start):
    visited = []
    stack = Stack()
    stack.push(start)
    while not stack.isEmpty():
        vertex = stack.pop()
        if vertex not in visited:
            visited.append(vertex)
            print "VERTEX", vertex
            for edges in graph[vertex]:
                stack.push(edges)
    return visited
 def dfs_stack(self, v):
     """ Return a DFS tree from v, using a stack. """
     marked = {v:None}
     stack = Stack()
     stack.push(v)
     while stack.length() > 0:
         vertex = stack.pop()
         for e in self.get_edges(vertex):
             w = e.opposite(vertex)
             if w not in marked:
                 marked[w] = e
                 stack.push(w)
     return marked
示例#38
0
def sortAscendingOrder(s1):
    s2 = Stack()
    while not s1.isEmpty():
        # print 'S2:', s2.stack()
        # print 'S1:', s1.stack()
        last = s1.pop()
        while (not s2.isEmpty() and s2.peek() > last):
            s1.push(s2.pop())
        s2.push(last)
    return s2
示例#39
0
def find_closing_paren(string, start_paren):
    paren_stack = Stack()
    for i in range(start_paren, len(string)):
        ch = search_string[i]
        if ch == "(":
            paren_stack.push("(")
        elif ch == ")":
            paren_stack.pop()
            if paren_stack.is_empty():
                return i
示例#40
0
文件: q3_2.py 项目: keithxm23/CTCI
class minStack(Stack):
	
	def __init__(self):
		super(minStack,self).__init__()
		self.minSta = Stack()
			

	def pop(self):
		if self.minSta.peek() != None and self.minSta.peek() >= self.peek():
			self.minSta.pop()
		return super(minStack, self).pop()

	def push(self, data):
		if self.minSta.peek() == None or self.minSta.peek() >= data:
			self.minSta.push(data)
		super(minStack, self).push(data)

	def peek(self):
		return super(minStack, self).peek()

	def min(self):
		return self.minSta.peek()
示例#41
0
def matching_parens(text):
    open_parens = Stack()
    for c in text:
        try:
            if c == "(":
                open_parens.push(c)
            elif c == ")":
                open_parens.pop()
        except AttributeError:
            return -1
    try:
        open_parens.pop()
        return 1
    except AttributeError:
        return 0
示例#42
0
文件: q3_5.py 项目: keithxm23/CTCI
class Queue():

	def __init__(self):
		self.base = Stack()
		self.buff = Stack()

	#insertion in O(n)
	def enqueue(self, data):
		while(True):
			try:
				self.buff.push(self.base.pop().data)
			except:
				self.base.push(data)
				while(True):
					try:
						self.base.push(self.buff.pop().data)
					except:
						break
				break

	#removal in O(1)
	def dequeue(self):
		return self.base.pop()
def palindromeChecker(string):
    """Checks if 'string' is a palindrome"""
    holder = Stack()
    temp = Stack()
    isTrue = True
    
    for char in string:
        """Check for valid character before pushing to holder stack """
        if 'a' <= char <= 'z' or 'A' <= char <= 'Z' or 0 <= char <= 9:
            holder.push(char)    
    for i in xrange(len(holder)):
        """Pops from holder and compares value in 'string' """
        if 'a' <= string[i] <= 'z' or 'A' <= string[i] <= 'Z' or '0' <= string[i] <= '9':
            temp.push(string[i])
            item = holder.pop()
            if item != temp.pop():
                isTrue = False
                return isTrue
            
    return isTrue
示例#44
0
文件: q3_5.py 项目: keithxm23/CTCI
	def __init__(self):
		self.base = Stack()
		self.buff = Stack()
def get_path(v, tree):
    """ Extract a path from root to v, from backwards search tree. """
    s = Stack()
    s.push(v)
    _get_path(v, tree, s)
    return s
示例#46
0
from signal_source import DiracSource, SineSource, CompoundSineSource
import pylab
from writers import WaveWriter, AiffWriter, MatWriter
from pylab_tools import ProbeResultsPlotter
import wave
import math

if __name__ == "__main__":
    r = AiffReader("samples/demo1_stereo.aif")
    # r = SineSource(channels=2, freq=100, amp=0.5, phase=math.pi / 2, length=1000)
    # r = DiracSource(channels = 1, length=1000)
    # r = SineSource(freq=1000, channels=2, length=1000)
    # r = CompoundSineSource([dict(freq=1000, amp=0.5), dict(freq=100, amp=2)], channels=2, length=1000)

    s = Stack(
        [
            (LowPassFilter(samplerate=r.rate, channels=r.channels), "output"),
            (RMS(samplerate=r.rate, channels=r.channels), "rms"),
        ]
    )

    out = s.process_source(r)
    plotter = ProbeResultsPlotter(s.probe_results, figure_name=1)
    plotter.plot()
    pylab.show()

    w = AiffWriter("out.aif", r.channels, r.depth, r.rate)
    w.write(out[:20000])
    w.write(out[20000:])
    w.close()
示例#47
0
文件: q3_2.py 项目: keithxm23/CTCI
	def __init__(self):
		super(minStack,self).__init__()
		self.minSta = Stack()
示例#48
0
 def __init__(self):
     self.stack = Stack()
     self.largest = Stack()