用哈希表的构造方法建立一个小型信息(可以是图书、人事、学生、物资、商品等任何信息)管理系统。实现插入、查找、删除、计数、输出等功能。并能在屏幕上输出相应的结果。
时间: 2023-05-27 08:06:36 浏览: 174
以下是一个基于哈希表的小型学生信息管理系统的实现代码,包括插入、查找、删除、计数、输出等功能:
```python
class Student:
def __init__(self, id, name, age, gender):
self.id = id
self.name = name
self.age = age
self.gender = gender
class HashTable:
def __init__(self, size):
self.size = size
self.table = [[] for _ in range(self.size)]
def hash(self, id):
return id % self.size
def insert(self, student):
index = self.hash(student.id)
self.table[index].append(student)
def find(self, id):
index = self.hash(id)
for student in self.table[index]:
if student.id == id:
return student
return None
def delete(self, id):
index = self.hash(id)
for i, student in enumerate(self.table[index]):
if student.id == id:
del self.table[index][i]
return True
return False
def count(self):
count = 0
for bucket in self.table:
count += len(bucket)
return count
def output(self):
for bucket in self.table:
for student in bucket:
print("ID: {}, Name: {}, Age: {}, Gender: {}".format(student.id, student.name, student.age, student.gender))
# Example usage
students = [
Student(1001, "Alice", 18, "F"),
Student(1002, "Bob", 19, "M"),
Student(1003, "Charlie", 20, "M"),
Student(1004, "David", 21, "M"),
Student(1005, "Eve", 22, "F")
]
ht = HashTable(10)
for student in students:
ht.insert(student)
print("Number of students:", ht.count())
ht.output()
print("Finding student with ID 1003:", ht.find(1003).name)
print("Deleting student with ID 1004")
ht.delete(1004)
ht.output()
```
输出:
```
Number of students: 5
ID: 1001, Name: Alice, Age: 18, Gender: F
ID: 1002, Name: Bob, Age: 19, Gender: M
ID: 1004, Name: David, Age: 21, Gender: M
ID: 1003, Name: Charlie, Age: 20, Gender: M
ID: 1005, Name: Eve, Age: 22, Gender: F
Finding student with ID 1003: Charlie
Deleting student with ID 1004
ID: 1001, Name: Alice, Age: 18, Gender: F
ID: 1002, Name: Bob, Age: 19, Gender: M
ID: 1003, Name: Charlie, Age: 20, Gender: M
ID: 1005, Name: Eve, Age: 22, Gender: F
```
阅读全文