Python: Implementing a hash table that uses double hashing Your hash table class
ID: 3603339 • Letter: P
Question
Python: Implementing a hash table that uses double hashing
Your hash table class will be called HashTable.
You will need to modify the put() and delete() functions discussed in class. You will also need to implement a number of your own functions. This should be done in steps as listed below:
Programme: Python
com Hashiable import HashTabl: In Lectures 26 and 27 e discussed the mplementatien of &hash; table bat used linear probing for collision resolution In this esercise you will modity this hash table class so that it uses double hating for colisio, resolution. The hash table will also increase its size whenever its lod icor0.75 or moe. 1 he lash table will contin key-dana pairs. You can assume that keys will be imeger values and data strings import. random aninal_1iat "rvark". "hall"cat "dog". "lphant.". "lrog pzint ("Tear 1 h table HahTabiet tor i in range l1enlaninil 11st): self, data" [None] +sell. 22 Your hash table class will be called Hashable. The constructor for this class has no parameter. Five instance variables will be initialized: def hashfunction!^^!r, rey, 12e) - zuen kay e size- the size of the hash table in the hach table alota - a python list with alze umber of elements print (h tabler"count:lenth tble a python lst wi number or ekmants. . deleted- string oonsistg of the null character " tor 1 1n range lien anins1-11st): You will need to modify the put1 and daleca) tanctioas discussed in class. Ycu wil also need to implement a number of yor oa functions. This sould be done in steps as listed belou position while self._lots (position -one: prine (a tabie, ountlenable) print I. Modify the pat (I and deletefunctions so that the variable cont is altered appropriated whenever kry-data, pair isadded t» er delted from the hash table. Chane te Lan function so that it retums this count 2. Your hash table will use the remainder mechod as discussed in lectures: print(- key % size. For collision resolution you will need to implement a second hash function: size-(key %(size-1)+1). You will need to alter the impemenlation of the rehash(I function o u this scand hash fundtion You will oimplment function al eneulales the losd aor e lash able. Rmember thar the oad facso is caculared using the fom h: tor 1 in rangel len!aninil list ) 3 key random.randrange(1000) 4. To increase the size of the hash table you wan so find a prime number that det put (5e12,key,dara) print(h table, "count : ", len(n cable appeoximatcly doubles its curret siac. For example ifyour hach table hs siac of 7, you will be looking mcreasing the sze ohe b to 13. You will need to mp ement a function that finds the largest prime number in the range 1 - - hah_valr.haah utkey, ln(lf. ota t sel.alotshash_valual - ane r peint O selt hash table propriately and rehashes all eisting key-data pairs into the appropriate slots in the larger hash table. You will need to modify the patO unction to e this resizei function appropriaily next 10--2-1f.xeh2.3hina5h v 1ue, len(3e12. 10tj) next aloaif.rehash (next s1at, 1n lif. aloza han poidl a file far you to test your heh table class A2Q3 py. An esampleof selt.data[nexe_slot]-data selt._datalnex_lot]-data det delete (seltr key): loif.haan tunccion(es. lenelt. alats) ev in slotel.lotssicion] while ke in lot-None: position-elt.rehash lpasition, lenlselt._lata) t position-start_lot: return None reurn aelf.aalete key def aeienaai, key.daca det esiten elt, ker) eir, sel: de xepx dars pinto'. " repl:-2)Explanation / Answer
Classroom.java
package org.university.hardware;
import org.university.software.Course;
import org.university.hardware.Department;
import java.util.ArrayList;
public class Classroom {
private String room;
private ArrayList<Course> courses;
public Classroom() {
room = "Unknown";
courses = new ArrayList<Course>();
}
private int[] getTimeSlots()
{
int[] toReturn = new int[30];
int index = 0;
for (int i = 100; i <= 500; i += 100) {
for (int j = 1; j <= 6; j++) {
toReturn[index] = i + j;
index++;
}
}
return toReturn;
}
public void addCourse(Course aCourse)
{
boolean flag = false;
for (Course crs : courses) {
if (crs.compareSchedules(aCourse)) {
System.out.println(aCourse.getDepartment().getDepartmentName()
+ aCourse.getCourseNumber() + " conflicts with "
+ crs.getDepartment().getDepartmentName() + crs.getCourseNumber()
+ ". Conflicting time slot " + aCourse.getConflictSlots(crs).get(0)
+ ". " + aCourse.getDepartment().getDepartmentName()
+ aCourse.getCourseNumber() + " course cannot be added to "
+ room + "'s Schedule.");
flag = true;
break;
}
}
if (!flag)
{
courses.add(aCourse);
}
}
public void setRoomNumber(String newRoom)
{
room = newRoom;
}
public String getRoomNumber()
{
return room;
}
public void printSchedule() {
int[] timeSlots = getTimeSlots();
for (int time : timeSlots) {
String slot = "";
String className = "";
for (Course crs : courses) {
if (crs.getMeetingTime(time) != "") {
slot = crs.getMeetingTime(time);
className = crs.getDepartment().getDepartmentName()
+ crs.getCourseNumber() + " " + crs.getName();
break;
}
}
if (slot != "")
System.out.println(slot + " " + className);
}
}
}
Department.java
package org.university.hardware;
import org.university.software.Course;
import org.university.people.Student;
import org.university.people.Professor;
import org.university.people.Staff;
import java.util.ArrayList;
public class Department {
private String departmentName;
private ArrayList<Course> Courses;
private ArrayList<Student> Students;
private ArrayList<Professor> Professors;
private ArrayList<Staff> Staffers;
public Department()
{
departmentName = "unknown";
Courses = new ArrayList<Course>();
Students = new ArrayList<Student>();
Professors = new ArrayList<Professor>();
Staffers = new ArrayList<Staff>();
}
public String getDepartmentName()
{
return departmentName;
}
public void setDepartmentName(String adepartmentname)
{
departmentName = adepartmentname;
}
public void addStaff(Staff stf){
Staffers.add(stf);
if(stf.getDepartment() == null || stf.getDepartment() != this){
stf.setDepartment(this);
}
}
public ArrayList<Staff> getStaffList(){
return Staffers;
}
public void addProfessor(Professor prof){
Professors.add(prof);
if(prof.getDepartment() == null || prof.getDepartment() != this){
prof.setDepartment(this);
}
}
public ArrayList<Professor> getProfessorList(){
return Professors;
}
public void addStudent(Student student){
Students.add(student);
if(!student.getDepartment().equals(this))
student.setDepartment(this);
}
public ArrayList<Student> getStudentList(){
return Students;
}
public void addCourse(Course course){
Courses.add(course);
if(!course.getDepartment().equals(this))
course.setDepartment(this);
}
public ArrayList<Course> getCourseList(){
return Courses;
}
public void printStudentList(){
for(Student s : Students){
System.out.println(s.getName());
}
}
public void printProfessorList(){
for(Professor p : Professors){
System.out.println(p.getName());
}
}
public void printStaffList(){
for(Staff st : Staffers){
System.out.println(st.getName());
}
}
public void printCourseList(){
for(Course c : Courses){
System.out.println(c.getName() + c.getCourseNumber());
}
}
}
Employee.java
package org.university.people;
public abstract class Employee extends Person {
private double payRate;
public Employee() {
payRate = 0.0;
}
public double getPayRate()
{
return payRate;
}
public void setPayRate(double pr)
{
payRate = pr;
}
public void raise(double percent) {
payRate += (percent / 100.0) * payRate;
}
public abstract double earns();
}
Person.java
package org.university.people;
import java.util.ArrayList;
import org.university.software.Course;
public abstract class Person {
private String name;
private ArrayList<Course> courses;
public Person(){
courses = new ArrayList<Course>();
}
private int[] getTimeSlots(){
int[] toReturn = new int[30];
int index = 0;
for(int i = 100; i <= 500; i += 100){
for(int j = 1; j <= 6; j++){
toReturn[index] = i + j;
index++;
}
}
return toReturn;
}
public void setName(String newName){
name = newName;
}
public String getName(){
return name;
}
public ArrayList<Course> getCourses(){
return courses;
}
public boolean detectConflict(Course aCourse){
for(Course course : courses){
if(course.compareSchedules(aCourse)){
ArrayList<String> conflicts = course.getConflictSlots(aCourse);
for(String conflict : conflicts){
System.out.println(aCourse.getDepartment().getDepartmentName()
+ aCourse.getCourseNumber() + " course cannot be added to "
+ name + "'s Schedule. " + aCourse.getDepartment().getDepartmentName()
+ aCourse.getCourseNumber() + " conflicts with "
+ course.getDepartment().getDepartmentName()
+ course.getCourseNumber() + ". Conflicting time slot is "
+ conflict + ".");
}
return true;
}
}
return false;
}
public void printSchedule(){
for(int time : getTimeSlots())
for(Course crs : courses)
if(crs.getMeetingTime(time) != "")
System.out.println(crs.getMeetingTime(time)
+ " " + crs.getDepartment().getDepartmentName()
+ crs.getCourseNumber() + " " + crs.getName());
}
public abstract void addCourse(Course aCourse);
}
Professor.java
package org.university.people;
import org.university.hardware.Department;
import org.university.software.Course;
public class Professor extends Employee {
private Department dept;
public Professor(){
dept = null;
}
public void setDepartment(Department newDept){
dept = newDept;
}
public Department getDepartment(){
return dept;
}
@Override
public double earns() {
return 200 * super.getPayRate();
}
@Override
public void addCourse(Course aCourse) {
if(aCourse.getProfessor() != null){
System.out.println("The professor cannot be assigned to this course"
+ " because professor " + aCourse.getProfessor().getName()
+ " is already assigned to the course " + aCourse.getName() + ".");
}
else if(!detectConflict(aCourse)){
aCourse.setProfessor(this);
super.getCourses().add(aCourse);
}
}
}
Staff.java
package org.university.people;
import org.university.software.Course;
import org.university.hardware.Department;
public class Staff extends Employee {
private Department dept;
private double hoursWorked;
public Staff(){
hoursWorked = 0.0;
dept = null;
}
public void setMonthlyHours(double hours){
hoursWorked = hours;
}
public double getMonthlyHours(){
return hoursWorked;
}
public void setDepartment(Department dept){
this.dept = dept;
}
public Department getDepartment(){
return dept;
}
@Override
public double earns() {
return hoursWorked * super.getPayRate();
}
@Override
public void addCourse(Course aCourse) {
if(super.getCourses().size() > 0){
System.out.println(super.getCourses().get(0).getDepartment().getDepartmentName()
+ super.getCourses().get(0).getCourseNumber() + " is removed from "
+ super.getName() + "'s schedule(Staff can only take one class at a time). "
+ aCourse.getDepartment().getDepartmentName() + aCourse.getCourseNumber()
+ " has been added to " + super.getName() + "'s Schedule.");
super.getCourses().get(0).removeStudent(this);
super.getCourses().remove(0);
}
super.getCourses().add(aCourse);
aCourse.addStudent(this);
}
}
Student.java
package org.university.people;
import org.university.software.Course;
import org.university.hardware.Department;
public class Student extends Person {
private Department dept;
private int unitsCompleted;
private int totalUnitsNeeded;
public Student(){
dept = new Department();
unitsCompleted = 0;
totalUnitsNeeded = 0;
}
public void setCompletedUnits(int units){
unitsCompleted = units;
}
public int getUnitsCompleted(){
return unitsCompleted;
}
public int requiredToGraduate(){
return totalUnitsNeeded - unitsCompleted;
}
public void setRequiredCredits(int units){
totalUnitsNeeded = units;
}
public int getTotalUnits(){
return totalUnitsNeeded;
}
public void setDepartment(Department dept){
this.dept = dept;
if(!this.dept.getStudentList().contains(this)){
this.dept.addStudent(this);
}
}
public Department getDepartment(){
return dept;
}
public void addCourse(Course crs){
if(!detectConflict(crs)){
super.getCourses().add(crs);
if(!crs.getStudentRoster().contains(this))
crs.addStudent(this);
}
}
public void dropCourse(Course crs){
if(super.getCourses().contains(crs)){
super.getCourses().remove(crs);
if(crs.getStudentRoster().contains(this))
crs.removeStudent(this);
}
else{
System.out.println("The course " + crs.getDepartment().getDepartmentName()
+ crs.getCourseNumber() + " could not be "
+ "dropped because " + super.getName() + " is not enrolled in "
+ crs.getDepartment().getDepartmentName()
+ crs.getCourseNumber() + ".");
}
}
}
Course.java
package org.university.software;
import java.util.ArrayList;
import org.university.people.Person;
import org.university.hardware.Department;
import org.university.hardware.Classroom;
import org.university.people.Professor;
import org.university.people.Staff;
import org.university.people.Student;
public class Course {
private String[] Week = {"Mon", "Tue", "Wed", "Thu", "Fri"};
private String[] Slot = {"8:00am to 9:15am",
"9:30am to 10:45am",
"11:00am to 12:15pm",
"12:30pm to 1:45pm",
"2:00pm to 3:15pm",
"3:30pm to 4:45pm"};
private String name;
private int number;
private ArrayList<Integer> schedule;
private ArrayList<Person> roster;
private Department dept;
private Classroom room;
private Professor prof;
public Course(){
name = "";
number = -1;
prof = null;
schedule = new ArrayList<Integer>();
roster = new ArrayList<Person>();
dept = new Department();
}
public String getMeetingTime(int timeSlot){
if(schedule.contains(timeSlot))
return Week[timeSlot / 100 - 1] + " " + Slot[timeSlot % 10 - 1];
return "";
}
public void printSchedule(){
for(int timeSlot : schedule){
System.out.println(getMeetingTime(timeSlot) + " " + room.getRoomNumber());
}
}
public void printRoster(){
for(Person snt : roster){
System.out.println(snt.getName());
}
}
public void setRoomAssigned(Classroom newRoom){
newRoom.addCourse(this);
room = newRoom;
}
public Classroom getRoomAssigned(){
return room;
}
public boolean compareSchedules(Course other){
for(Integer timeSlot : other.schedule){
if(schedule.contains(timeSlot))
return true;
}
return false;
}
public void setName(String name){
this.name = name;
}
public String getName(){
return name;
}
public void setProfessor(Professor prof){
this.prof = prof;
}
public Professor getProfessor(){
return prof;
}
public void setCourseNumber(int num){
number = num;
}
public int getCourseNumber(){
return number;
}
public void setSchedule(int addNum){
schedule.add(addNum);
}
public ArrayList<Integer> getSchedule(){
return schedule;
}
public void setDepartment(Department dept){
this.dept = dept;
if(!this.dept.getCourseList().contains(this))
this.dept.addCourse(this);
}
public Department getDepartment(){
return dept;
}
public void addStudent(Person student){
roster.add(student);
if(!student.getCourses().contains(this)){
student.addCourse(this);
}
}
public void removeStudent(Student student){
roster.remove(student);
if(student.getCourses().contains(this)){
student.dropCourse(this);
}
}
public void removeStudent(Staff student){
roster.remove(student);
}
public ArrayList<Person> getStudentRoster(){
return roster;
}
public ArrayList<String> getConflictSlots(Course aCourse){
ArrayList<String> toReturn = new ArrayList<String>();
for(Integer timeSlot : aCourse.schedule){
if(schedule.contains(timeSlot))
toReturn.add(getMeetingTime(timeSlot));
}
return toReturn;
}
}
Driver1.java
package org.university.software;
import org.university.hardware.Classroom;
import org.university.hardware.Department;
import org.university.people.Professor;
import org.university.people.Student;
import org.university.people.Staff;
/* Test driver by Lahiru Ariyananda and Peter Hall */
public class Driver1
{
public static void main(String[] args)
{
/* Initialize University */
University univ = new University();
/*
* Create University of department, classrooms, professors,
* students, staff.
*/
/* Set Department */
Department dept1 = new Department();
Department dept2 = new Department();
/* Set Student */
Student s1 = new Student();
Student s2 = new Student();
Student s3 = new Student();
Student s4 = new Student();
/* Set Course */
Course c1 = new Course();
Course c2 = new Course();
Course c3 = new Course();
Course c4 = new Course();
Course c5 = new Course();
Course c6 = new Course();
Course c7 = new Course();
Course c8 = new Course();
/* Set Room */
Classroom cr1 = new Classroom();
Classroom cr2 = new Classroom();
Classroom cr3 = new Classroom();
Classroom cr4 = new Classroom();
/* Set Professor */
Professor p1 = new Professor();
Professor p2 = new Professor();
Professor p3 = new Professor();
Professor p4 = new Professor();
Professor p5 = new Professor();
/* Set Staff */
Staff sf1 = new Staff();
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.