def test_dequeue():
    queue = PriorityQueue()
    queue.enqueue("a")
    queue.enqueue("b")

    assert queue.dequeue() == "b"
    assert len(queue) == 1
def test_dequeue_empty_queue():
    queue = PriorityQueue()

    with pytest.raises(IndexError) as exc:
        queue.dequeue()

    assert str(exc.value) == "dequeue from empty priority queue"
def test_peek_empty_queue():
    queue = PriorityQueue()

    with pytest.raises(IndexError) as exc:
        queue.peek()

    assert str(exc.value) == "peek from empty priority queue"
def test_assign_priority_via_insert():
    new_pq = PriorityQueue()
    for i in range(5):
        new_pq.insert(Job(priority=i+1))
    new_pq.jobs[-1].time_created -= 100
    new_pq.insert(Job(priority=6))
    assert [job.priority for job in new_pq.jobs] == [8, 5, 6, 1, 4, 2]
    def test_insert(self):
        pq = PriorityQueue()
        pq.add_element(1)

        self.assertTrue(pq.elements[0] == 1)
        for i in xrange(1, len(pq.elements)):
            self.assertTrue(pq.elements[i] is None)
def test_enqueue(items, expected_head):
    queue = PriorityQueue()
    for item in items:
        queue.enqueue(item)

    assert len(queue) == len(items)
    assert queue.peek() == expected_head
def test_priority_queue_empty(make_jobs):
    pq = PriorityQueue()
    assert pq.jobs == []
    assert pq._operations == 0
    pq = PriorityQueue(make_jobs)
    temp = [p.priority for p in pq.jobs]
    assert temp == [9, 9, 9, 7, 8, 3, 7, 3, 7, 4]
def test_peek():
    queue = PriorityQueue()
    queue.enqueue("a")
    queue.enqueue("b")

    assert queue.peek() == "b"
    assert len(queue) == 2
def new_pq():
    pq = PriorityQueue()
    for index, value in enumerate([3,  3,  4,  9,  7,  7,  9,  9,  7,  8]):
        pq.insert(Job(priority=value))
        if not index % 3:
            pq._operations = 0
    pq._operations = 0
    return pq
    def test_insert3(self):
        pq = PriorityQueue()
        pq.add_element(5)
        pq.add_element(4)
        pq.add_element(6)

        self.assertTrue(pq.elements[0] == 6)
        self.assertTrue(pq.elements[1] == 4)
        self.assertTrue(pq.elements[2] == 5)
        for i in xrange(3, len(pq.elements)):
            self.assertTrue(pq.elements[i] is None)
def test_assign_priority_via_pop():
    new_pq = PriorityQueue()
    for _ in range(4):
        new_pq.insert(Job(priority=1))
    new_pq.jobs[3].time_created -= 100
    new_pq.pop()
    assert [job.priority for job in new_pq.jobs] == [6, 1, 1]
    new_pq.jobs[2].time_created -= 100
    new_pq._operations = 4
    new_pq.pop()
    assert [job.priority for job in new_pq.jobs] == [6, 1]
def test_assign_priority_via_pop():
    new_pq = PriorityQueue()
    for i in range(5):
        new_pq.insert(Job(priority=i + 1))
    new_pq.jobs[-1].time_created -= 100
    new_pq.insert(Job(priority=6))
    new_pq.pop()
    assert [job.priority for job in new_pq.jobs] == [6, 5, 1, 4, 2]
Beispiel #13
0
def search(start: Vertex.Vertex, goal: Vertex.Vertex, graph: Graph.Graph, f, g, h):
    f_score = dict();
    f_score[start] = h(start, goal);
    g_score = collections.defaultdict(lambda: sys.maxsize);
    g_score[start] = 0;
    open_list = PriorityQueue.PriorityQueue();
    open_list.add_task(start);
    came_from = dict();
    discovered = collections.defaultdict(lambda: False);
    discovered[start] = True;

    while open_list:
        current = open_list.pop_task();
        discovered[current] = True;

        if(current == goal):
            return generate_path.reconstruct_path(came_from, current);

        neighbors = current.get_neighbors();
        for x in neighbors:

            tentative_gScore =  g_score[current] + g(current, x);
            if tentative_gScore < g_score[x]:
                came_from[x] = current;
                g_score[x] = tentative_gScore;
                f_score[x] = f(g_score[x], h(x, goal));

                if not discovered[x]:
                    open_list.add_task(x, f_score[x]);
    return None;
Beispiel #14
0
def search(start: Vertex.Vertex, graph: Graph.Graph):
    unvisited_set = set(graph.vert_dict.values())
    goal = set(graph.vert_dict.values())
    f_score = collections.defaultdict(lambda: sys.maxsize)
    visited_set = set()
    f_score[start] = 0
    open_list = PriorityQueue.PriorityQueue()
    open_list.add_task(start)
    came_from = dict()

    while open_list:
        current = open_list.pop_task()
        visited_set.add(current)
        unvisited_set.remove(current)

        if visited_set == goal:
            path = generate_path.reconstruct_path(came_from, current)
            path.append(list(graph.vert_dict.values())[0])
            return path

        for x in unvisited_set:
            tentative_fscore = graph.vert_dict[current.get_id()].get_weight(
                x) + mst_heuristic(start, current, unvisited_set)
            if x not in open_list or x not in visited_set:
                f_score[x] = tentative_fscore
                open_list.add_task(x, f_score[x])

            if x in open_list or x in visited_set and tentative_fscore < f_score[
                    x]:
                came_from[x] = current
                f_score[x] = tentative_fscore
                if (x in visited_set):
                    unvisited_set.add(x)

    return None
Beispiel #15
0
def search(start, goal, map, f, g, h):
    f_score = dict()
    f_score[start] = h(start, goal)
    g_score = collections.defaultdict(lambda: sys.maxsize)
    g_score[start] = 0
    open_list = PriorityQueue.PriorityQueue()
    open_list.add_task(start)
    came_from = dict()
    discovered = collections.defaultdict(lambda: False)
    discovered[start] = True

    while open_list:
        current = open_list.pop_task()
        discovered[current] = True

        if (current == goal):
            return generate_path.reconstruct_path(came_from, current)

        neighbors = current.get_neighbors()
        for x in neighbors:

            tentative_gScore = g_score[current] + g(current, x)
            if tentative_gScore < g_score[x]:
                came_from[x] = current
                g_score[x] = tentative_gScore
                f_score[x] = f(g_score[x], h(x, goal))

                if not discovered[x]:
                    open_list.add_task(x, f_score[x])
    return None
def test_assign_priority_via_pop():
    new_pq = PriorityQueue()
    for _ in range(4):
        new_pq.insert(Job(priority=1))
    new_pq.jobs[3].time_created -= 100
    new_pq.pop()
    assert [job.priority for job in new_pq.jobs] == [6,  1,  1]
    new_pq.jobs[2].time_created -= 100
    new_pq._operations = 4
    new_pq.pop()
    assert [job.priority for job in new_pq.jobs] == [6,  1]
Beispiel #17
0
def dijkstra(aGraph, start):
    pq = PriorityQueue()
    start.set_distance(0)
    pq.build_heap([(v, v.get_distance()) for v in aGraph])
    while not pq.is_empty():
        current_vert = pq.dequeue()[0]
        for next_vert in current_vert.get_connections():
            new_dist = current_vert.get_distance() + current_vert.get_weight(
                next_vert)
            if new_dist < next_vert.get_distance():
                next_vert.set_distance(new_dist)
                next_vert.set_pred(current_vert)
                pq.decrease_priority(next_vert, new_dist)
def test_iter():
    queue = PriorityQueue()
    queue.enqueue("a")
    queue.enqueue("c")
    queue.enqueue("b")

    assert [item for item in queue] == ["c", "b", "a"]
Beispiel #19
0
def prim(aGraph, start):
    pq = PriorityQueue()
    for v in aGraph:
        v.set_distance(maxsize)
        v.set_pred(None)
    start.set_distance(0)
    pq.build_heap([(v, v.get_distance()) for v in aGraph])
    while not pq.is_empty():
        current_vert = pq.dequeue()[0]
        for next_vert in current_vert.get_connections():
            new_cost = current_vert.get_weight(next_vert)
            if next_vert in pq and new_cost < next_vert.get_distance():
                next_vert.set_distance(new_cost)
                next_vert.set_pred(current_vert)
                pq.decrease_priority(next_vert, new_cost)
def new_pq():
    pq = PriorityQueue()
    for index, value in enumerate([3, 3, 4, 9, 7, 7, 9, 9, 7, 8]):
        pq.insert(Job(priority=value))
        if not index % 3:
            pq._operations = 0
    pq._operations = 0
    return pq
Beispiel #21
0
    def test_enqueue(self):
        queue = PriorityQueue()
        priority_item_one = PriorityItem("item1", 1)
        priority_item_two = PriorityItem("item2", 1)

        queue.enqueue(priority_item_one)
        queue.enqueue(priority_item_two)
        front = queue.front()

        assert len(queue) == 2
        assert front.value == priority_item_one.value
        assert front.priority == priority_item_one.priority

        priority_item_three = PriorityItem("item3", 2)
        queue.enqueue(priority_item_three)
        front = queue.front()

        assert len(queue) == 3
        assert front.value == priority_item_three.value
        assert front.priority == priority_item_three.priority
    def test_delete(self):
        pq = PriorityQueue()
        pq.add_element(5)
        pq.add_element(4)
        pq.add_element(6)
        pq.add_element(6)
        pq.add_element(3)
        pq.add_element(7)

        self.assertTrue(pq.elements[0] == 7)
        self.assertTrue(pq.elements[1] == 6)
        self.assertTrue(pq.elements[2] == 6)
        self.assertTrue(pq.elements[3] == 4)
        self.assertTrue(pq.elements[4] == 3)
        self.assertTrue(pq.elements[5] == 5)

        for i in xrange(6, len(pq.elements)):
            self.assertTrue(pq.elements[i] is None)

        res = pq.pop()
        self.assertTrue(res == 7)
Beispiel #23
0
def mst(g: Graph.Graph):
    min_tree = Graph.Graph()
    open_list = PriorityQueue.PriorityQueue()
    cost = collections.defaultdict(lambda: sys.maxsize)
    for x in g.vert_dict.values():
        open_list.add_task(x, cost[x])
    edge = collections.defaultdict(lambda: False)

    while open_list:
        current = open_list.pop_task()
        min_tree.add_vertex(current.get_id())
        if edge[current]:
            min_tree.add_edge(current.get_id(), edge[current][0].get_id(),
                              edge[current][1])
        for x in current.get_neighbors():
            if x in open_list and current.get_weight(x) < cost[x]:
                cost[x] = current.get_weight(x)
                edge[x] = (current, cost[x])
                open_list.add_task(x, cost[x])
    return min_tree
class PriorityQueueTest(unittest.TestCase):

    def setUp(self):
        self.queue = PriorityQueue()

    @istest
    def starts_at_zero_size(self):
        self.assertEqual(0, len(self.queue))

    @istest
    def can_push_an_elements(self):
        self.queue.push('a')
        self.assertEqual(1, len(self.queue))

    @istest
    def can_push_multiple_elements(self):
        self.queue.push('a')
        self.queue.push('b')
        self.queue.push('c')
        self.assertEqual(3, len(self.queue))

    @istest
    def can_pop_an_element(self):
        expected_element = 'a'
        self.queue.push(expected_element)
        self.assertEqual(expected_element,  self.queue.pop())
        self.assertEqual(0, len(self.queue))

    @istest
    def can_pop_multiple_element(self):
        expected_output = set(['a', 'b', 'c'])
        for item in expected_output:
            self.queue.push(item)
        actual_output = set()
        while self.queue:
            actual_output.add(self.queue.pop())
        self.assertEqual(expected_output,  actual_output)
        self.assertEqual(0, len(self.queue))

    @istest
    def can_pop_items_in_priority_order(self):
        self.queue.push('a', 10)
        self.queue.push('b', 50)
        self.queue.push('c', 1)

        self.assertEqual('c', self.queue.pop())
        self.assertEqual('a', self.queue.pop())
        self.assertEqual('b', self.queue.pop())

    @istest
    def no_priority_defaults_to_lowest_priority(self):
        self.queue.push('a')
        self.queue.push('b', 99)
        self.assertEqual('b', self.queue.pop())
        self.assertEqual('a', self.queue.pop())

    @istest
    def remove_elements(self):
        self.queue.push('a', 9)
        self.queue.push('b', 99)
        self.queue.remove('a')
        self.assertEqual(1, len(self.queue))
        self.assertEqual('b', self.queue.pop())
        self.assertEqual(0, len(self.queue))

    @istest
    def empty_queue_throws_key_error(self):
        with self.assertRaises(KeyError):
            self.queue.pop()
        with self.assertRaises(KeyError):
            self.queue.push('a')
            self.queue.pop()
            self.queue.pop()
        with self.assertRaises(KeyError):
            self.queue.push('b')
            self.queue.remove('b')
            self.queue.pop()

    @istest
    def can_update_priority(self):
        self.queue.push('a', 99)
        self.queue.push('b', 10)
        self.assertEqual(2, len(self.queue))
        self.queue.update('a', 3)
        self.assertEqual(2, len(self.queue))
        self.assertEqual('a', self.queue.pop())
        self.assertEqual('b', self.queue.pop())
        self.assertEqual(0, len(self.queue))
 def setUp(self):
     self.queue = PriorityQueue()
Beispiel #26
0
    def test_dequeue(self):
        queue = PriorityQueue()
        priority_item_one = PriorityItem("item1", 1)
        priority_item_two = PriorityItem("item2", 3)
        priority_item_three = PriorityItem("item3", 99)
        queue.enqueue(priority_item_one)
        front_item = queue.front()

        assert len(queue) == 1
        assert front_item.value == priority_item_one.value
        assert front_item.priority == priority_item_one.priority

        dequed_value = queue.dequeue()

        assert len(queue) == 0
        assert dequed_value.value == priority_item_one.value
        assert dequed_value.priority == priority_item_one.priority
        assert queue.dequeue() == None

        queue.enqueue(priority_item_three)
        queue.enqueue(priority_item_one)
        queue.enqueue(priority_item_two)

        assert queue.dequeue().value == priority_item_three.value
        assert queue.dequeue().value == priority_item_two.value
        assert queue.dequeue().value == priority_item_one.value
    def test_batch_increment(self):
        pq = PriorityQueue()
        pq.add_element(Deneme('a', 1))
        pq.add_element(Deneme('b', 5))
        pq.add_element(Deneme('b', 10))
        pq.add_element(Deneme('a', 7))
        pq.add_element(Deneme('a', 9))
        pq.add_element(Deneme('b', 12))

        self.assertTrue(pq.elements[0].val == 12)
        self.assertTrue(pq.elements[1].val == 9)
        self.assertTrue(pq.elements[2].val == 10)
        self.assertTrue(pq.elements[3].val == 1)
        self.assertTrue(pq.elements[4].val == 7)
        self.assertTrue(pq.elements[5].val == 5)

        for i in xrange(6, len(pq.elements)):
            self.assertTrue(pq.elements[i] is None)

        def validate(obj):
            return obj.label == 'a'

        def update(obj):
            obj.val += 1

        pq.batch_increment(validate, update)
        self.assertTrue(pq.elements[0].val == 12)
        self.assertTrue(pq.elements[1].val == 10)
        self.assertTrue(pq.elements[2].val == 10)
        self.assertTrue(pq.elements[3].val == 2)
        self.assertTrue(pq.elements[4].val == 8)
        self.assertTrue(pq.elements[5].val == 5)
def test_empty_pop():
    pq = PriorityQueue()
    with pytest.raises(IndexError):
        pq.pop()
def test_priority_queue_sequence(make_jobs):
    pq = PriorityQueue(make_jobs)
    temp = [p.priority for p in pq.jobs]
    assert temp == [9, 9, 9, 7, 8, 3, 7, 3, 7, 4]
def test_empty_pop():
    pq = PriorityQueue()
    with pytest.raises(IndexError):
        pq.pop()