Reputation: 111
I am creating a package delivery program. I created a custom chaining hash table, and a packages class that reads from a CSV and inserts the data into the hash table. How do I go about printing the newly created custom Hash Table to make sure it is entering the data correctly? I have tried multiple different things and end up not being able to print it at all. Thank you for your time.
Here is the hash table .insert method that I am using:
class HashTable:
# Constructor
# Space-time complexity is O(1)
def __init__(self, initial_capacity=40):
# initialize the hash table with empty bucket list entries.
self.table = []
for i in range(initial_capacity):
self.table.append([])
# Created this private method to create hash keys in the other methods
# Space-time complexity is O(1)
def _get_key(self, key):
hash_key = int(key) % len(self.table)
return hash_key
# Insert a new package value into the hash table
# Space-time complexity is O(N)
def insert(self, key, value):
hash_key = self._get_key(key)
key_value = [key, value]
if self.table[hash_key] is None:
self.table[hash_key] = list([key_value])
return True
else:
for i in self.table[hash_key]:
if i[0] == key:
i[1] = key_value
return True
self.table[hash_key].append(key_value)
return True
Package class:
import csv
from HashTable import HashTable
class Package:
def __init__(self, package_id, address, delivery_time):
self.package_id = package_id
self.address = address
self.delivery_time = delivery_time
IN_ROUTE = 'in_route'
DELIVERED = 'delivered'
AVAILABLE_AT_HUB = 'at_hub'
# Open file
with open('WGUData.csv') as packages_file:
# create a reader object
reader = csv.reader(packages_file, delimiter=',')
# Inserts data into table
insert_into_package_hash = HashTable()
package_list = []
# read each line of the file
for row in reader:
package = Package(row[0], row[1], row[5])
package_list.append(package)
key = package.package_id
value = (package.address, package.delivery_time)
insert_into_package_hash.insert(key, value)
The print that makes sense to me :
print(insert_into_package_hash)
but that returns error, repeating:
<HashTable.HashTable object at 0x0000022BE6FDF370>
<HashTable.HashTable object at 0x0000022BE6FDF370>
Upvotes: 0
Views: 1028
Reputation: 420
If you want a string representation of your object (HashTable) you need to overload the __str__
method in your class definition.
Something like
def __str__(self):
return "foo"
but returning the data within your HashTable instance as a formatted string.
Upvotes: 2