def __init__(self, g):
     self.edge_set = []
     self.g = g
     self.heap = MaxHeap()
     self.UF = UnionFind(g.V)
     self.populateHeap()
     self.populate_edge_set()
Example #2
0
 def test_sift_down(self):
     """
     Sifting down an element swaps it with the larger of its two children,
     and continues to sift down that element in its new position and its new
     children, until it is in a position where it obeys the heap property.
     Hint: This might only require one more line of code, if expressed recursively.
     """
     h = MaxHeap()
     h._data.append(2)
     h._data.append(9)
     h._data.append(10)
     h._data.append(5)
     h._data.append(4)
     h._data.append(7)
     h._data.append(6)
     h._data.append(1)
     h._sift_down(0)
     self.assertEqual(10, h._data[0])
     self.assertEqual(9, h._data[1])
     self.assertEqual(7, h._data[2])
     self.assertEqual(5, h._data[3])
     self.assertEqual(4, h._data[4])
     self.assertEqual(2, h._data[5])
     self.assertEqual(6, h._data[6])
     self.assertEqual(1, h._data[7])
Example #3
0
 def test_heap_property_one(self):
     """
     A heap with one element obeys the max-heap property.
     """
     h = MaxHeap()
     h._data.append('fake')
     self.assertTrue(h._obeys_heap_property_at_index(0))
    def find_key_events_by_word(self,
                                word,
                                max_events_per_year,
                                years,
                                include_score=False):
        """
        find events closest to the given word
        """
        if not word:
            return None
        word = word.lower()
        key_years_to_events = OrderedDict([(year, []) for year in years])
        for key_year in years:
            model = self.get_model(key_year)
            # find the key events from that year
            top_key_events = MaxHeap(max_events_per_year)
            # take the events that are most similar to the event
            events = self.get_relevant_events(key_year)
            for e in events:
                if word in self.event_to_content[
                        e] and model.contains_all_words([e, word]):
                    similarity = model.similarity(e, word)
                    if similarity > self.knn_threshold:
                        top_key_events.add(similarity, e)
            top_key_events = sorted(top_key_events.heap, reverse=True)
            key_years_to_events[key_year] = [
                item[1] + '--' +
                str(round(item[0], 2)) if include_score else item[1]
                for item in top_key_events
            ]

        return key_years_to_events
 def test_insert_stable(self):
     """
     An inserted value that is smaller than its parent will remain in the new
     leaf position.
       10            10
      /  \   =>    /    \
     8    4       8      4
                 / \    / \
                3   4  1   2
     """
     h = MaxHeap()
     h.insert(10)
     h.insert(8)
     h.insert(4)
     h.insert(3)
     h.insert(4)
     h.insert(1)
     h.insert(2)
     self.assertEqual(10, h._data[0])
     self.assertEqual(8, h._data[1])
     self.assertEqual(4, h._data[2])
     self.assertEqual(3, h._data[3])
     self.assertEqual(4, h._data[4])
     self.assertEqual(1, h._data[5])
     self.assertEqual(2, h._data[6])
Example #6
0
 def test_greater_child_index_one(self):
     """
     The 'greater child index' of an element without children is None.
     """
     h = MaxHeap()
     h._data.append('fake')
     self.assertIsNone(h._greater_child_index(0))
 def test_insert_empty(self):
     """
     An empty MaxHeap stores a new value as the root. No algorithms necessary.
     """
     h = MaxHeap()
     h.insert(10)
     self.assertEqual(10, h._data[0])
 def test_last_index_initial(self):
     """
     The 'last index' of an empty heap happens to be -1.
     Hint: Easy to calculate if you know its size.
     """
     h = MaxHeap()
     self.assertEqual(-1, h._last_index())
 def test_sift_up(self):
     """
     Sifting up an element swaps it with its parent when appropriate, and
     continues to sift up that element from its new position, until it either
     becomes the root or its parent's value is larger than its value.
     """
     h = MaxHeap()
     h._data.append(600)
     h._data.append(500)
     h._data.append(8)
     h._data.append(7)
     h._data.append(6)
     h._data.append(5)
     h._data.append(4)
     h._data.append(3)
     h._data.append(2)
     h._data.append(1)
     h._data.append(42)
     h._sift_up(10)
     self.assertEqual(600, h._data[0])
     self.assertEqual(500, h._data[1])
     self.assertEqual(8, h._data[2])
     self.assertEqual(7, h._data[3])
     self.assertEqual(42, h._data[4])
     self.assertEqual(5, h._data[5])
     self.assertEqual(4, h._data[6])
     self.assertEqual(3, h._data[7])
     self.assertEqual(2, h._data[8])
     self.assertEqual(1, h._data[9])
     self.assertEqual(6, h._data[10])
    def find_events_from_wikipedia_baseline(self,
                                            word,
                                            max_events_per_year,
                                            years,
                                            include_score=False,
                                            min_occurrences=5):
        """
        find for each given year: events that contain the given word the most times
        """
        if not word:
            return None
        word = word.lower()
        key_years_to_events = OrderedDict([(year, []) for year in years])
        for key_year in years:
            # find the key events from that year
            top_key_events = MaxHeap(max_events_per_year)
            # take the events that are most similar to the event
            for e in self.year_to_event[key_year]:
                # count number of occurrences of the given word in the Wiki content
                score = sum(1 for _ in re.finditer(
                    r'\b%s\b' %
                    re.escape(word), self.event_to_text_content[e].lower()))
                if score > min_occurrences:
                    top_key_events.add(score, e)
            top_key_events = sorted(top_key_events.heap, reverse=True)
            key_years_to_events[key_year] = [
                item[1] + '--' +
                str(round(item[0], 2)) if include_score else item[1]
                for item in top_key_events
            ]

        return key_years_to_events
 def test_insert_unstable_six(self):
     """
     An inserted value that is larger than its parent should sift up until
     the heap property is obeyed.
          10               10
        /    \   =>      /    \
       8      4         8      9
      / \    /         / \    / \
     1   3  2         1   3  2   4
     """
     h = MaxHeap()
     h.insert(10)
     h.insert(8)
     h.insert(4)
     h.insert(1)
     h.insert(3)
     h.insert(2)
     h.insert(9)
     self.assertEqual(10, h._data[0])
     self.assertEqual(8, h._data[1])
     self.assertEqual(9, h._data[2])
     self.assertEqual(1, h._data[3])
     self.assertEqual(3, h._data[4])
     self.assertEqual(2, h._data[5])
     self.assertEqual(4, h._data[6])
class MinWTFeedbackEdgeSet:
    def __init__(self, g):
        self.edge_set = []
        self.g = g
        self.heap = MaxHeap()
        self.UF = UnionFind(g.V)
        self.populateHeap()
        self.populate_edge_set()

    def populateHeap(self):
        edges = set()
        for i in range(self.g.V):
            for edge in self.g.adj(i):
                edges.add(edge)
        for edge in edges:
            self.heap.add_item(edge)

    def populate_edge_set(self):
        #import pdb; pdb.set_trace()
        while not self.heap.empty():
            edge = self.heap.del_max()
            if not self.UF.find(edge.either(), edge.other(edge.either())):
                self.UF.union(edge.either(), edge.other(edge.either()))
            else:
                self.edge_set.append(edge)
                    
    def get_mst(self):
        return self.edge_set
 def test_empty_initial(self):
     """
     A new heap is empty.
     Hint: _size is a convenient abstraction, and helps avoid repetitive code.
     """
     h = MaxHeap()
     self.assertTrue(h._is_empty())
 def test_last_index_42(self):
     """
     The last index of a heap with forty-two elements is 41.
     """
     h = MaxHeap()
     for _ in range(42):
         h._data.append('fake')
     self.assertEqual(41, h._last_index())
 def test_value_at_zero(self):
     """
     The value at index 0 is the value of the 0th item in the heap's data list.
     """
     h = MaxHeap()
     value = fake_value()
     h._data.append(value)
     self.assertEqual(value, h._value_at(0))
 def test_last_index_two(self):
     """
     The last index of a heap with two elements is 1.
     """
     h = MaxHeap()
     h._data.append('fake')
     h._data.append('fake')
     self.assertEqual(1, h._last_index())
 def test_last_index_one(self):
     """
     The last index of a heap with one element is 0.
     Hint: Easy, if you know how to determine the last index of a list.
     """
     h = MaxHeap()
     h._data.append('fake')
     self.assertEqual(0, h._last_index())
Example #18
0
 def test_sift_up_one(self):
     """
     Sifting up the root is easy.
     Hint: Be naive for now.
     """
     h = MaxHeap()
     h._data.append(1)
     h._sift_up(0)
     self.assertEqual(1, h._data[0])
Example #19
0
 def test_greater_child_index_left_only(self):
     """
     The 'greater child index' of an element with just a left child (no right
     child) returns the index of that left child.
     """
     h = MaxHeap()
     h._data.append('fake')
     h._data.append('fake')
     self.assertEqual(1, h._greater_child_index(0))
 def test_delete_one(self):
     """
     Deleting when there is only one element removes that element
     and returns it.
     """
     h = MaxHeap()
     h.insert(10)
     self.assertEqual(10, h.delete())
     self.assertEqual(0, len(h._data))
Example #21
0
 def test_sift_down_one(self):
     """
     Sifting down the root of a single-element heap is easy.
     Hint: Be naive for now.
     """
     h = MaxHeap()
     h._data.append(1)
     h._sift_down(0)
     self.assertEqual(1, h._data[0])
Example #22
0
def heap_sort(*arr):
    arr = list(arr)

    heap = MaxHeap(arr)
    arr = []
    for i in range(len(arr) - 1, -1, -1):
        arr[i] = heap.remove()

    return arr
 def test_not_empty(self):
     """
     A heap is not empty if there are items in its data list.
     """
     h = MaxHeap()
     h._data.append('fake')
     self.assertFalse(h._is_empty())
     h._data.append('fake')
     self.assertFalse(h._is_empty())
 def test_empty(self):
     """
     A heap with no items in its data list is empty.
     """
     h = MaxHeap()
     h._data.append('fake')
     h._data.append('fake')
     h._data = []
     self.assertTrue(h._is_empty())
 def test_insert_larger_one(self):
     """
     An inserted value that is larger than the root becomes the root, and the
     root becomes the left child.
     """
     h = MaxHeap()
     h.insert(10)
     h.insert(15)
     self.assertEqual(15, h._data[0])
     self.assertEqual(10, h._data[1])
Example #26
0
 def test_heap_property_two_obey(self):
     """
     A heap with two elements, with a parent value greater than its left
     child's value obeys the max-heap property.
     """
     h = MaxHeap()
     h._data.append(10)
     h._data.append(5)
     self.assertTrue(h._obeys_heap_property_at_index(0))
     self.assertTrue(h._obeys_heap_property_at_index(1))
Example #27
0
 def test_greater_child_index_left(self):
     """
     The 'greater child index' of an element with a left and right child, is
     the index of the left child when it has a value greater than or equal to
     the right child.
     """
     h = MaxHeap()
     h._data.append(10)
     h._data.append(5)
     h._data.append(1)
     self.assertEqual(1, h._greater_child_index(0))
 def test_size_data(self):
     """
     The _size() of a heap is equal to the number of values in its list.
     """
     h = MaxHeap()
     h._data.append('fake')
     self.assertEqual(1, h._size())
     h._data.append('fake')
     self.assertEqual(2, h._size())
     h._data.pop()
     self.assertEqual(1, h._size())
class PriorityQueue:
    def __init__(self):
        self.heap = MaxHeap()

    def enqueue(self, value):
        self.heap.insert(value)

    def dequeue(self):
        return self.heap.delete()

    def is_empty(self):
        return self.heap._size() == 0
 def test_right_child_index(self):
     """
     An element at index i has a right child at index ____.
     Hint: Know how the heap works. Look up and study the concept.
     """
     h = MaxHeap()
     # This method just calculates the index. It doesn't care about the data.
     self.assertEqual(2, h._right_child_index(0))
     self.assertEqual(4, h._right_child_index(1))
     self.assertEqual(6, h._right_child_index(2))
     self.assertEqual(8, h._right_child_index(3))
     self.assertEqual(5446, h._right_child_index(2722))
def main():
    frontier = MaxHeap()
    goal = PlayTypeByTurn('Snake', 5)
    
    initial_state = init_state()
    frontier.insert((initial_state, goal.score_func(initial_state)))
    
    goal_state = None
    while frontier.size() > 0:
        best_candidate = frontier.extract()
        print("current candidate: " + str(best_candidate[1]) + " " + best_candidate[0].describe())
        if goal.goal_func(best_candidate[0]):
            goal_state = best_candidate[0]
            break
        frontier.insert_list([entry for entry in [(child, goal.score_func(child)) for child in generate_children(best_candidate[0])] if entry[1] > 0])
    
    if not goal_state:
        print('Goal unachievable')
        return
    
    current = goal_state
    goal_to_start = [current]
    while current.parent:
        current = current.parent
        goal_to_start.append(current)
    
    for state in goal_to_start[::-1]:
        print(state.prev_action)