Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

import copy # Implementation of a heap in python # We use a list for the data in place of an array, as the list

image text in transcribed

import copy

# Implementation of a heap in python

# We use a list for the data in place of an array, as the list allow

# index-based access.

class Heap:

def __init__(self):

self.data = [] # Empty heap

def extractMax(self):

max= self.data[0]

self.data[0] = self.data[len(self.data)-1]

self.data.pop() # removes last element

self.heapify(0)

return max

# Don't need to pass in heap size, can compute from data[]

# The objects in the heap must have defined

def heapify(self, i):

largest = i # Initialize largest as root

left = 2*i + 1 # Formula for 0-based array

right = 2*i + 2

heapSize = len(self.data)

if (left self.data[largest]):

largest = left

if (right self.data[largest]):

largest = right

if (largest != i):

temp = self.data[i]

self.data[i] = self.data[largest]

self.data[largest] = temp

self.heapify(largest)

def buildHeap(self, sourceList):

self.data = copy.deepcopy(sourceList) # Makes deep copy of list

for i in range(len(self.data) - 1, -1, -1): # i-1 down to 0

self.heapify(i)

# Insert will be left for you to implement in an upcoming assignment

def insert(self, element):

return

2. (12 points) Heap Implementation Start with the python heap implementation given in the colab notebook. 1. Complete the insert method so that an element is properly inserted into the heap. 2. Create a Person class that has two instance variables, one for name and the other for age. You can add additional variables and methods if you like but it should have those two at a minimum with an appropriate _init_method. You should define == for the Person class based on lexicographically comparing the name as well as an implementation for Str. 3. In your main program create 6 Person objects with the name age of your choice and insert them into a heap. Make a loop that extracts the maximum until the heap is empty, outputting each name. This should result in outputting the people in reverse alphabetical order by name

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Database Systems An Application Oriented Approach Complete Version

Authors: Michael Kifer, Arthur Bernstein, Richard Lewis

2nd Edition

0321268458, 978-0321268457

More Books

Students also viewed these Databases questions

Question

How many Tables Will Base HCMSs typically have? Why?

Answered: 1 week ago

Question

What is the process of normalization?

Answered: 1 week ago