如何使用二进制搜索查找pickle对象属性

时间:2018-06-04 03:09:08

标签: python object pickle binary-search

我正在创建一个程序,作为一个存储学生的数据库,作为对象。每个对象(学生)都有三个属性:名称,等级和平均值。我正在尝试合并二进制搜索,以便用户可以搜索平均值。如果在对象的某个属性中找到平均值,则程序应显示该对象。现在我正试图让二进制搜索工作;如果我搜索存储在偶数索引中的平均值,那么它可以工作,但它不适用于任何奇数索引。有谁知道为什么会这样?此外,我试图显示包含正在搜索的平均值的对象,但到目前为止,我只能显示包含搜索平均值的对象的索引位置。任何帮助显示对象将不胜感激!

我的计划如下:

import pickle

class Student():
    def __init__(self,nam,grd,avg):
        self.name = nam
        self.grade = grd
        self.average = avg

    def get_details(self):
        print(self.name, self.grade, self.average)

def unpickle_database(filename):
    with open(filename, 'rb') as f:
        while True:
            try:
                yield pickle.load(f)
            except EOFError:
                break

def display_database():
    print("\nName:               Grade:              Average:            ")
    for student in unpickle_database('student_data.pkl'):
        property_list = [student.name, student.grade, student.average]
        print(''.join([v.ljust(20,' ') for v in property_list]))

def store_averages_in_list():
    students = list(unpickle_database('student_data.pkl'))
    students_average = []
    for student in students:
        students_average.append(int(student.average))
    return students_average

def bin_search(x, type):
    my_list = list(sorted(store_students_in_list(), key=attrgetter(type), reverse=False))
    bottom = 0
    top = len(my_list)-1
    found = False
    location = -1
    while (bottom <= top) and not(found):
        middle = int((bottom + top)/2)

        if (my_list[middle] == x):
            location = middle
            found = True
        elif (my_list[middle] < x):
            bottom = middle + 1
        else:
            top = middle -1
    return location

while True:
    user_input = input()
    if user_input == "Search":
        print(bin_search(int(input("Enter average to search for: ")),'average'))

0 个答案:

没有答案