PYTHON Create A Class, Call It MaxPriorityQueue Which Represents A Max Heap. You Only Need To Change

PYTHON Create A Class, Call It MaxPriorityQueue Which Represents A Max Heap. You Only Need To Change
PYTHON Create A Class, Call It MaxPriorityQueue Which Represents A Max Heap. You Only Need To Change ≪ To ≫ In Method Add. You Will Use Both Class SortedPriorityQueue And MaxPriorityQeueue To Solve The Problem Of Finding The Median Value Of A Stream Of Integers. Median Is The Middle Value Of An Ordered Data Set. For A Set Of Integers, There Are Just As     PYTHON Create a class, call it MaxPriorityQueue which represents a max heap. You only need to change < to=""> in method add. You will use both class SortedPriorityQueue and MaxPriorityQeueue to solve the problem of finding the median value of a stream of integers. Median is the middle value of an ordered data set. For a set of integers, there are just as many elements less than the median as greater. In an ordered set of: odd number of integers, the middle element is the median – in the ordered set { 5, 7, 8, 10, 15 }, the median is 8 even number of integers, there's no middle element; the median is computed as the average of the two middle elements – in the ordered set {5, 7, 8, 10}, the median is (7 + 8) / 2 = 7.5 Assume that instead of a finite set, we're reading integers off a data stream. We can define the median of a stream of integers as the median of the set of integers read so far. To solve the problem, we can use two heaps, one holds the lower half and another for the upper half, and keep them balanced, they only differ in size by 1. Max heap: keeps numbers of the lower half, so the root of the heap is the max value Min heap: keeps the numbers of the upper half, the root of the heap is the min value With these two heaps, we can compute the effective (current) median, by only reading the root(s), which is a O(1) operation. But the solution complexity is O(nlogn). Here is an algorithm that describes the solution, your task is to implement the algorithm. Emulate the stream of numbers by randomly generated values of your choice, when each number is generated, you need to compute the median of the numbers generated so far. Algorithm Create two heaps. One max heap (maxheap) to maintain elements of the lower half and one min heap(minheap) to maintain elements of the higher half at any point in time. Initially, the value of median is 0. For the current element received from the stream insert it into either of the heaps and calculate the median described in the following statements. If the size of both the heaps is the same. if the current element is greater than the median value, insert it into min heap, return the root of minheap as the new median. else if the current element is less than the median value, insert it into max heap, return the root of maxheap as the new median. else If the size of maxheap is greater than minheap : if the current element is greater than the median, insert the current element in minheap. else if the current element is less than the median, pop the root of maxheap and insert it into minheap. Now insert the current element to maxheap. calculate the median as an average of the root of minheap and maxheap. else If the size of maxheap is less than minheap : if the current element is less than the median, insert the current element into maxheap. else if the current element is greater than the median, pop the top of minheap and insert it into maxheap. Now insert the current element to minheap. calculate the median as an average of the root of minheap and maxheap. SortedPriorityQueue.py —————————- from priorityqueue.PriorityQueueBase import PriorityQueueBase from linkedlists import PositionalList import priorityqueue.Empty   class SortedPriorityQueue(PriorityQueueBase): # base class defines _Item   “””A min-oriented priority queue implemented with a sorted list.”””     #—————————— public behaviors ——————————   def __init__(self):     “””Create a new empty Priority Queue.”””     self._data = PositionalList()     def __len__(self):     “””Return the number of items in the priority queue.”””     return len(self._data)     def add(self, key, value):     “””Add a key-value pair.”””     newest = self._Item(key, value)             # make new item instance     walk = self._data.last()       # walk backward looking for smaller key     while walk is not None and newest <>       walk = self._data.before(walk)     if walk is None:       self._data.add_first(newest)              # new key is smallest     else:       self._data.add_after(walk, newest)        # newest goes after walk     def min(self):     “””Return but do not remove (k,v) tuple with minimum key.       Raise Empty exception if empty.     “””     if self.is_empty():       raise Empty('Priority queue is empty.')     p = self._data.first()     item = p.element()     return (item._key, item._value)     def remove_min(self):     “””Remove and return (k,v) tuple with minimum key.       Raise Empty exception if empty.     “””     if self.is_empty():       raise Empty('Priority queue is empty.')     item = self._data.delete(self._data.first())     return (item._key, item._value) PriorityQueueBase.py ——————————— class PriorityQueueBase:   “””Abstract base class for a priority queue.”””     #—————————— nested _Item class ——————————   class _Item:     “””Lightweight composite to store priority queue items.”””     __slots__ = '_key', '_value'       def __init__(self, k, v):       self._key = k       self._value = v       def __lt__(self, other):       return self._key <>    # compare items based on their keys       def __repr__(self):       return '({0},{1})'.format(self._key, self._value)     #—————————— public behaviors ——————————   def is_empty(self):                  # concrete method assuming abstract len     “””Return True if the priority queue is empty.”””     return len(self) == 0     def __len__(self):     “””Return the number of items in the priority queue.”””     raise NotImplementedError('must be implemented by subclass')     def add(self, key, value):     “””Add a key-value pair.”””     raise NotImplementedError('must be implemented by subclass')     def min(self):     “””Return but do not remove (k,v) tuple with minimum key.       Raise Empty exception if empty.     “””     raise NotImplementedError('must be implemented by subclass')     def remove_min(self):     “””Remove and return (k,v) tuple with minimum key.       Raise Empty exception if empty.     “””     raise NotImplementedError('must be implemented by subclass') PositionalList.py ——————————– from linkedlists.DoublyLinkedList import _DoublyLinkedBase     class PositionalList(_DoublyLinkedBase):     “””A sequential container of elements allowing positional access.”””       # ————————– nested Position class ————————–     class Position:         “””An abstraction representing the location of a single element.           Note that two position instances may represent the same inherent         location in the list.  Therefore, users should always rely on         syntax 'p == q' rather than 'p is q' when testing equivalence of         positions.         “””           def __init__(self, container, node):             “””Constructor should not be invoked by user.”””             self._container = container             self._node = node           def element(self):             “””Return the element stored at this Position.”””             return self._node._element           def __eq__(self, other):             “””Return True if other is a Position representing the same location.”””             return type(other) is type(self) and other._node is self._node           def __ne__(self, other):             “””Return True if other does not represent the same location.”””             return not (self == other)  # opposite of __eq__       # ——————————- utility methods ——————————-     def _validate(self, p):         “””Return position's node, or raise appropriate error if invalid.”””         if not isinstance(p, self.Position):             raise TypeError('p must be proper Position type')         if p._container is not self:             raise ValueError('p does not belong to this container')         if p._node._next is None:  # convention for deprecated nodes             raise ValueError('p is no longer valid')         return p._node       def _make_position(self, node):         “””Return Position instance for given node (or None if sentinel).”””         if node is self._header or node is self._trailer:             return None  # boundary violation         else:             return self.Position(self, node)  # legitimate position       # ——————————- accessors ——————————-     def first(self):         “””Return the first Position in the list (or None if list is empty).”””         return self._make_position(self._header._next)       def last(self):         “””Return the last Position in the list (or None if list is empty).”””         return self._make_position(self._trailer._prev)       def before(self, p):         “””Return the Position just before Position p (or None if p is first).”””         node = self._validate(p)         return self._make_position(node._prev)       def after(self, p):         “””Return the Position just after Position p (or None if p is last).”””         node = self._validate(p)         return self._make_position(node._next)       def __iter__(self):         “””Generate a forward iteration of the elements of the list.”””         cursor = self.first()         while cursor is not None:             yield cursor.element()             cursor = self.after(cursor)       # ——————————- mutators ——————————-     # override inherited version to return Position, rather than Node     def _insert_between(self, e, predecessor, successor):         “””Add element between existing nodes and return new Position.”””         node = super()._insert_between(e, predecessor, successor)         return self._make_position(node)       def add_first(self, e):         “””Insert element e at the front of the list and return new Position.”””         return self._insert_between(e, self._header, self._header._next)       def add_last(self, e):         “””Insert element e at the back of the list and return new Position.”””         return self._insert_between(e, self._trailer._prev, self._trailer)       def add_before(self, p, e):         “””Insert element e into list before Position p and return new Position.”””         original = self._validate(p)         return self._insert_between(e, original._prev, original)       def add_after(self, p, e):         “””Insert element e into list after Position p and return new Position.”””         original = self._validate(p)         return self._insert_between(e, original, original._next)       def delete(self, p):         “””Remove and return the element at Position p.”””         original = self._validate(p)         return self._delete_node(original)  # inherited method returns element       def replace(self, p, e):         “””Replace the element at Position p with e.           Return the element formerly at Position p.         “””         original = self._validate(p)         old_value = original._element  # temporarily store old element         original._element = e  # replace with new element         return old_value  # return the old element value DoublyLinkedList.py ———————— class _DoublyLinkedBase:   “””A base class providing a doubly linked list representation.”””     #————————– nested _Node class ————————–   # nested _Node class   class _Node:     “””Lightweight, nonpublic class for storing a doubly linked node.”””     __slots__ = '_element', '_prev', '_next'            # streamline memory       def __init__(self, element, prev, next):            # initialize node's fields       self._element = element                           # user's element       self._prev = prev                                 # previous node reference       self._next = next                                 # next node reference     #————————– list constructor ————————–     def __init__(self):     “””Create an empty list.”””     self._header = self._Node(None, None, None)     self._trailer = self._Node(None, None, None)     self._header._next = self._trailer                  # trailer is after header     self._trailer._prev = self._header                  # header is before trailer     self._size = 0                                      # number of elements     #————————– public accessors ————————–     def __len__(self):     “””Return the number of elements in the list.”””     return self._size     def is_empty(self):     “””Return True if list is empty.”””     return self._size == 0     #————————– nonpublic utilities ————————–     def _insert_between(self, e, predecessor, successor):     “””Add element e between two existing nodes and return new node.”””     newest = self._Node(e, predecessor, successor)      # linked to neighbors     predecessor._next = newest     successor._prev = newest     self._size += 1     return newest     def _delete_node(self, node):     “””Delete nonsentinel node from the list and return its element.”””     predecessor = node._prev     successor = node._next     predecessor._next = successor     successor._prev = predecessor     self._size -= 1     element = node._element                             # record deleted element     node._prev = node._next = node._element = None      # deprecate node     return element                                      # return deleted element
May 13 2022 07:27 PM

Place your order
(550 words)

Approximate price: $22

Calculate the price of your order

550 words
We'll send you the first draft for approval by September 11, 2018 at 10:52 AM
Total price:
$26
The price is based on these factors:
Academic level
Number of pages
Urgency
Basic features
  • Free title page and bibliography
  • Unlimited revisions
  • Plagiarism-free guarantee
  • Money-back guarantee
  • 24/7 support
On-demand options
  • Writer’s samples
  • Part-by-part delivery
  • Overnight delivery
  • Copies of used sources
  • Expert Proofreading
Paper format
  • 275 words per page
  • 12 pt Arial/Times New Roman
  • Double line spacing
  • Any citation style (APA, MLA, Chicago/Turabian, Harvard)

Our guarantees

Delivering a high-quality product at a reasonable price is not enough anymore.
That’s why we have developed 5 beneficial guarantees that will make your experience with our service enjoyable, easy, and safe.

Money-back guarantee

You have to be 100% sure of the quality of your product to give a money-back guarantee. This describes us perfectly. Make sure that this guarantee is totally transparent.

Read more

Zero-plagiarism guarantee

Each paper is composed from scratch, according to your instructions. It is then checked by our plagiarism-detection software. There is no gap where plagiarism could squeeze in.

Read more

Free-revision policy

Thanks to our free revisions, there is no way for you to be unsatisfied. We will work on your paper until you are completely happy with the result.

Read more

Privacy policy

Your email is safe, as we store it according to international data protection rules. Your bank details are secure, as we use only reliable payment systems.

Read more

Fair-cooperation guarantee

By sending us your money, you buy the service we provide. Check out our terms and conditions if you prefer business talks to be laid out in official language.

Read more
Open chat
1
You can contact our live agent via WhatsApp! Via + 1 (409) 205-8984

Feel free to ask questions, clarifications, or discounts available when placing an order.

Order your essay today and save 30% with the discount code DISCOUNT