예제 #1
0
class MyQueue:

	def __init__(self):
		self.queue = Stack()


	def add(self, item):
		self.queue.push(item)


	def remove(self):
		temp = self.queue.reverse()
		res = temp.pop()
		self.queue = temp.reverse()
		return res


	def peek(self):
		temp = self.queue.reverse()
		res = temp.peek()
		self.queue = temp.reverse()
		return res


	def is_empty(self):
		return self.queue.is_empty()


	def __str__(self):
		return str(self.queue)
예제 #2
0
파일: p04.py 프로젝트: jake-albert/py-algs
def get_path(graph, from_s, from_t):
    """Traces the searchers to create and return a list of indices 
    representing the shortest path from s to t. Assumes that the 
    search is already complete and that a path has been found.
    
    Args:
        graph: A Graph instance.
        from_s, from_t: Searcher instances.
        
    Returns:
        A list of integers.
    """
    path = []

    # We first construct the path from s to the connection point. Using
    # a stack ensures that the order is correct.

    start_stack = Stack()
    while from_s.backtracer is not None:
        start_stack.push(from_s.backtracer)
        from_s.backtracer = graph[from_s.backtracer].backpointer

    while not start_stack.is_empty():
        path.append(start_stack.pop())

    # Then we extend the path from the connection point to t.

    while from_t.backtracer is not None:
        path.append(from_t.backtracer)
        from_t.backtracer = graph[from_t.backtracer].backpointer

    return path
예제 #3
0
class SetOfStacks:

    max_items = 3

    def __init__(self):
        self.piles = Stack()
        self._create_new_stack()


    def _create_new_stack(self):
        self.piles.push(Stack())


    def push(self, item):
        if self.piles.peek().size() == self.max_items:
            self._create_new_stack()
            self.push(item)
        else:
            self.piles.peek().push(item)


    def pop(self):
        return self.piles.peek().pop()


    def pop_stack(self):
        return Stack.pop(self.piles)


    def is_empty(self):
        return self.piles.is_empty()


    def _backfill(self, new, old):
        while new.size() > 0:
            old.push(new.pop())


    def pop_at(self, index):
        if index > self.piles.size()-1:
            raise "Invalid index."
        temp_stack = Stack()
        for i in range(index, 0, -1):
            temp_stack.push(SetOfStacks.pop_stack(self))
        item = self.piles.pop()
        self._backfill(temp_stack.reverse(), self.piles)
        return item.pop()


    def __str__(self):
        if not self.is_empty():
            return Stack.__str__(self.piles)
        return "Stack is empty."
예제 #4
0
def test_stack_with_no_elements_is_empty():
    s = Stack()
    assert s.is_empty()