Exemplo n.º 1
0
    def dft(self, starting_vertex_id):
        """
        Traverse and print each vertex in depth-first order (DFT) beginning from starting_vertex.
        """
        # Initialize empty stack and set of visited nodes:
        stack = Stack()
        visited = set()

        # Check if provided starting vertex is in our graph:
        if starting_vertex_id in self.vertices.keys():
            # If so, add starting vertex to stack:
            stack.push(starting_vertex_id)
        else:
            return IndexError(
                f"Provided starting vertex {starting_vertex_id} does not exist in graph!"
            )

        # Process all vertices via BFT:
        while stack.size() > 0:
            # Get next vertex to process as first item in stack:
            current_vertex = stack.pop()
            # If the current vertex has not already been visited+processed, process it:
            if current_vertex not in visited:
                # Process current vertex:
                print(current_vertex)
                # Add adjacent vertices to stack for future processing:
                for adjacent_vertex in self.get_neighbors(current_vertex):
                    stack.push(adjacent_vertex)
                # Mark current vertex as "visited" by adding to our set of visited vertices:
                visited.add(current_vertex)
Exemplo n.º 2
0
    def dfs(self, starting_vertex, target_vertex):
        """
        Return a list containing the shortest path from starting_vertex to destination_vertex, 
        after searching for and finding it with a depth-first search (DFS) algorithm.
        """
        # Initialize empty stack and set of visited nodes:
        stack = Stack()
        visited = set()

        # Initialize path (we will add the rest of the path from starting vertex to target vertex below):
        path = [starting_vertex]

        # Check if provided starting vertex is in our graph:
        if starting_vertex in self.vertices.keys():
            # If so, add starting vertex to stack:
            stack.push(path)
        else:
            return IndexError(
                f"Provided starting vertex {starting_vertex} does not exist in graph!"
            )

        # Process all vertices via BFT:
        while stack.size() > 0:
            # Get next vertex to process as first item in stack:
            current_path = stack.pop()
            current_vertex = current_path[-1]
            # If the current vertex has not already been visited+processed, check and process it:
            if current_vertex not in visited:
                # Check if it is the target --> if so, return its full path:
                if current_vertex == target_vertex:
                    return current_path
                # If not, then get its neighbor vertices and add their paths to the stack for future processing:
                for adjacent_vertex in self.get_neighbors(current_vertex):
                    adjacent_vertex_path = current_path + [adjacent_vertex]
                    stack.push(adjacent_vertex_path)
                # Mark current vertex as "visited" by adding to our set of visited vertices:
                visited.add(current_vertex)

        # If no path found in entire graph, return None:
        return None
Exemplo n.º 3
0
class TestStack(unittest.TestCase):  # LIFO

    def setUp(self):
        self.emptyStack = Stack()
        self.Stack = Stack()

        for i in range(5):
            self.Stack.push(i)

    def test_repr(self):
        '''Test returning the stack as a string literal.'''
        self.assertEqual(repr(self.emptyStack), str(()))
        tup = (1, 3.14, 'foo', True)

        for i in tup:
            self.emptyStack.push(i)

        self.assertEqual(repr(self.emptyStack), str((True, 'foo', 3.14, 1)))

    def test_len_size(self):
        '''Test returning the size of the stack.'''
        for i in range(100):
            self.emptyStack.push(i)

        self.assertEqual(len(self.emptyStack), 100)
        self.assertEqual(self.emptyStack.size(), 100)

        self.emptyStack.pop()
        self.assertEqual(len(self.emptyStack), 99)
        self.assertEqual(self.emptyStack.size(), 99)

    def test_tuple(self):
        '''Test returning the stack as a tuple literal.'''
        self.assertEqual(tuple(self.emptyStack), ())
        tup = (1, 3.14, 'foo', True)

        for i in tup:
            self.emptyStack.push(i)

        self.assertEqual(tuple(self.emptyStack), (True, 'foo', 3.14, 1))

    def test_list(self):
        '''Test returning the stack as a list literal.'''
        self.assertEqual(list(self.emptyStack), [])
        li = [1, 3.14, 'foo', True]

        for i in li:
            self.emptyStack.push(i)

        self.assertEqual(list(self.emptyStack), [True, 'foo', 3.14, 1])

    def test_push(self):
        '''Test pushing items on top of the stack.'''
        self.Stack.push(True)
        self.assertEqual(tuple(self.Stack), (True, 4, 3, 2, 1, 0))

    def test_pop(self):
        '''Test popping off and returning the top of the stack.'''
        self.assertEqual(self.Stack.pop(), 4)
        self.assertEqual(tuple(self.Stack), (3, 2, 1, 0))
        self.assertEqual(self.Stack.pop(), 3)
        self.assertEqual(self.Stack.pop(), 2)
        self.assertEqual(self.Stack.pop(), 1)
        self.assertEqual(self.Stack.pop(), 0)
        self.assertEqual(tuple(self.Stack), ())

        with self.assertRaises(ValueError):
            self.Stack.pop()

    def test_peek(self):
        '''Test peeking at the top of the stack w/o modifying the stack.'''
        self.assertEqual(self.Stack.peek(), 4)

        with self.assertRaises(ValueError):
            self.emptyStack.peek()
Exemplo n.º 4
0
from data_structures import Stack, Queue, Deque

stack = Stack()
queue = Queue()
deque = Deque()

print("*** Stack ***")
print(stack)

for i in range(5):
    stack.push(i)
    print(stack)
for i in range(stack.size()):
    stack.pop()
    print(stack)

print("*** Queue ***")
print(queue)

for i in range(5):
    queue.enqueue(i)
    print(queue)
for i in range(queue.size()):
    queue.dequeue()
    print(queue)

print("*** Deque - Stack operation ***")
print(deque)

for i in range(5):
    deque.add_rear(i)
Exemplo n.º 5
0
current_room = player.current_room

rooms_to_visit.push(current_room.id)

sort_order = [dir for dir in ["e", "w", "s", "n"]]
exits = sorted(current_room.get_exits(),
               key=lambda direction: sort_order.index(direction))
neighbors = {
    direction: current_room.get_room_in_direction(direction).id
    for direction in exits
}
# neighbors = {direction:current_room.get_room_in_direction(direction).id for direction in current_room.get_exits()}
neighbors["placeholder"] = 0  # [?? To do: REMOVE/fix this! ??]

while rooms_to_visit.size() > 0:
    # Get nearest room that is not yet visited from stack:
    next_room_id = rooms_to_visit.pop()

    # If the next room in our rooms_to_visit stack has not already been visited+processed, visit and process it:
    if next_room_id not in map.rooms:
        if next_room_id not in neighbors.values():
            assert set(neighbors.values()).issubset(map.rooms.keys())
            # If all of this room's neighbor's have already been explored:
            if set(neighbors.values()).issubset(map.rooms.keys()):
                # Go back:
                retrace_path = map.bfs(starting_room=current_room.id,
                                       target_room=next_room_id)

                for direction in retrace_path:
                    player.travel(direction=direction, show_rooms=True)
Exemplo n.º 6
0
from data_structures.Stack import *

Stack = Stack()

for i in range(0, 10):
    Stack.push(i)

length = Stack.size()
print('Stack size: ', length)

print('Elements on stack :')
for i in range(length):
    print(Stack.peak())
    Stack.pop()
def test_create_empty_stack():
    stack = Stack()

    assert stack.size() == 0
def test_create_stack_with_single_item():
    stack = Stack()
    stack.push('a')

    assert stack.size() == 1