Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
169 views
in Technique[技术] by (71.8m points)

performance - Can you solve this code without map (), zip and lambda? (will be replaced by other code)

class University: all_university = dict() # initializing constructor of university class def init(self, new_uni_id=0, new_uni_name='', new_base_pt=0, new_capacity=0): self.univ_id = new_uni_id self.univ_name = new_uni_name self.univ_base_point = new_base_pt self.univ_capacity = new_capacity

"""
This method will read all the records from university.txt and create object for each university after that
it will add object into all_university dictionary.
It is a static method because here we are reading a file and adding record so for using this method, we do not
need to create an object.
"""
@staticmethod
def read_university_record():
    file = open("university.txt", 'r')  # opening file in read mode
    for line in file.readlines(): # it will read each line one by one
        """
        Here line looks like, line = "1 , Ege University computer engineering , 300 , 5"
        so it needs to split every value and then create an object after that add that object into all_university
        dict
        """
        s_line = line.split(",") # it will separate all values by delimiter ","(comma) and create a list

        # now create an University object
        # Here strip() function used to wipe out accidental spaces
        new_univ_obj = University(int(s_line[0].strip()), s_line[1].strip(), int(s_line[2].strip()), int(s_line[3].strip()))

        # add newly created object into dict
        University.all_university[new_univ_obj.univ_id] = new_univ_obj
    # close the file
    file.close()

# this method print the university with maximum base point which is problem2
# it is static method because to find a university with max bas point we need not to create an object

def find_max_base_point():
    # it will find university with maximum base point by searching in all_university dict variable
    max_base_till_now = 0
    id_of_max_univ = None
    for obj in University.all_university.values():
        # if current university has greater base point as compare to previous one then update the values
        if obj.univ_base_point > max_base_till_now:
            max_base_till_now = obj.univ_base_point
            id_of_max_univ = obj.univ_id
    print("
--------------------University with maximum Base Point--------------------")
    # Now find that object from all_university dict
    obj = University.all_university[id_of_max_univ]
    print("University ID : ", obj.univ_id)
    print("University Name: ", obj.univ_name)
    print("Base Point : ", obj.univ_base_point)

def display_details(self):
    print("University ID : ", self.univ_id)
    print("University Name: ", self.univ_name)
    print("Base Point : ", self.univ_base_point)

student class

class Student: # like previous class, all_student dict here contain the information of all student # and it is a static variable so, we do not need to create an object to access them # these variable can be accessed by class name all_student = dict() # initializing constructor def init(self, new_id='', new_f_name='', new_l_name=''): # basic info of student self._student_id = '' # it is a private variable self.stud_first_name = new_f_name self.stud_last_name = new_l_name

    # students result info
    # initially all remain NULL, after reading record from answers.txt they will get updated
    self.stud_book_type = ''
    self.stud_correct_ans = 0
    self.stud_incorrect_ans = 0
    self.stud_blank_ans = 0
    self.stud_answers = 0 # number of answers after reducing the wrong ones based
    self.stud_score = 0
    self.stud_university_choice = []


    self.stud_placed_univ_id = None # id of place university
    self.stud_placed_univ_name = '' # name of placed university
    self.stud_placed_dep = ''
    self.stud_remark = "" # it will contain the info why student doesn't placed in it's given choice


# a getter function, user outside this class will access student_id as stud_id
@property
def stud_id(self):
    return self._student_id

# a setter function for setting private variable student_id
@stud_id.setter
def stud_id(self, new_id):
    # student id should have 6 characters
    if (len(new_id) < 6):
        raise ValueError("Sorry Student ID (%s) should have 6 characters!"%new_id)
    self._student_id = new_id

"""
This method will read all the records from student.txt and create object for each student after that
it will add object into all_student dictionary.
It is a static method because here we are reading a file and adding record so for using this method, we do not
need to create an object.
"""
@staticmethod
def read_student_record():
    file = open("student.txt", 'r') # opening file in read mode
    for line in file.readlines(): # it will read each line one by one
        # it will read a line here
        s_line = line.split(" ") # it will separate all values by delimiter " "(space) and create a list

        # now create an Student object
        # Here strip() function used to wipe out accidental spaces
        new_stud_obj = Student()
        new_stud_obj.stud_id = s_line[0].strip()
        new_stud_obj.stud_first_name = s_line[1].strip()
        new_stud_obj.stud_last_name = s_line[2].strip()
        # add newly created object into dict
        Student.all_student[new_stud_obj.stud_id] = new_stud_obj
    # close the file
    file.close()


"""
This method will read all the records from answers.txt and update already existing student's field
It is a static method because here we are reading a file and adding record so for using this method, we do not
need to create an object.
"""
@staticmethod
def read_students_answer_record():
    file = open("answers.txt", 'r') # opening answer file in read mode
    key_file = open("key.txt", 'r') # opening key file here because it will update students scores record

    # Here, it reads both answer keys in key_a and key_b respectively
    # it uses lambda function in-order to avoid newline
    key_a, key_b = map(lambda x: x.strip(), key_file.readlines())
    key_file.close()

    # Now read each line of answers.txt file one by one
    for line in file.readlines(): # it will read each line one by one
        # it will read a line here
        s_line = line.split(" ") # it will separate all values by delimiter " "(space) and create a list

        # now find already existing Student object
        current_stud_obj = Student.all_student.get(s_line[0].strip())
        # if the student with this id exist in our database then it will go further otherwise stop it there
        if current_stud_obj:
            # Now, if flow is here then it means student exist, and it needs to update further values

            # update students question book type
            current_stud_obj.stud_book_type = s_line[1].strip()

            # this line contain students response
            stud_answers = s_line[2].strip()

            # list of 2 university choices of student
            university_choice = [int(s_line[3].strip()), int(s_line[4].strip())]

            # now calculate right, wrong and blank answers
            right_ans, wrong_ans, blank_ans = 0, 0, 0

            # it will compare right answer with student's answer
            for stud_ans, correct_ans in zip(stud_answers, key_a if current_stud_obj.stud_book_type=="A" else key_b):
                if stud_ans == correct_ans:
                    right_ans += 1
                elif stud_ans == "*":
                    blank_ans += 1
                else:
                    wrong_ans += 1

            # Now lets calculate score
            score = (right_ans * 15) - (15 * (wrong_ans/4)) # each set of 4 wrong answers affect 1 right answer

            # Now update the object
            current_stud_obj.stud_correct_ans = right_ans
            current_stud_obj.stud_incorrect_ans = wrong_ans
            current_stud_obj.stud_blank_ans = blank_ans
            current_stud_obj.stud_answers = right_ans - wrong_ans//4 # number of answers after reducing the wrong ones based
            current_stud_obj.stud_score = score
            current_stud_obj.stud_university_choice = university_choice
        else:
            print("
Object Not Found Error!, Student with id: %s doesn't exist!!!!!!!!!!!!!
"%s_line[0])
    # close the file
    file.close()

@staticmethod
def create_result():
    # open file in write mode
    res_file = open("results.txt", 'w')
    # create header for file, here center is used to format string between spaces
    header = "Student ID".center(12, ' ') + "First Name".center(12, ' ')+ "Last Name".center(12, ' ') + 
            "Book Type".center(12, ' ') + "Correct Answers".center(18, ' ') + "Incorrect Answers".center(18, ' ')+
            "Blank Answers".center(15, ' ') + "Reduced Correct Answer".center(24, ' ') + "Score".center(12, ' ')
            +"Choice".center(8, ' ') + "
"

    res_file.write(header)
    # print(header)
    # Now writing the record of each student according to given specification
    for obj in Student.all_student.values():
        data = obj.stud_id.center(12, ' ') + obj.stud_first_name.center(12, ' ')+
            obj.stud_last_name.center(12, ' ')+ obj.stud_book_type.center(12, ' ')+
            str(obj.stud_correct_ans).center(18, ' ')+
            str(obj.stud_incorrect_ans).center(18, ' ')+
            str(obj.stud_blank_ans).center(15, ' ')+
            str(obj.stud_answers).center(24, ' ')+
            str(obj.stud_score).center(12, ' ')+
            str(obj.stud_university_choice).center(8, ' ') + "
"
        res_file.write(data)
        # print(data)
    print("
---------------------------Results written successfully in results.txt!---------------------------
")
    res_file.close()

@staticmethod
def print_students_details_sort_by_name():
    # first it needs to sort the dict all students based on students score
    # first create a list of all student object and then sort it based on score
    all_objects = list(Student.all_student.values())
    all_objects.sort(key=lambda x: x.stud_score)

    # Now print all the values
    print("
-------------------------Students Record sorted by Score-------------------------")
    print("Student ID".center(12, ' ') + "First Name".center(12, ' ') + "Last Name".center(12, ' ') + 
        "Score".center(12, ' '))
    for obj in all_objects:
        print(obj.stud_id.center(12, ' ') + obj.stud_first_name.center(12, ' ')+
            obj.stud_last_name.center(12, ' ') + str(obj.stud_score).center(12, ' '))


# it will take a student object and place it if possible and update instance of placement
def place_student(self):
    # first check whether student's answers are evaluated or not
    if self.stud_book_type != '':

        # first find out choice of university
        univ_choice1 = University.all_university.get(self.stud_university_choice[0])
        univ_choice2 = University.all_university.get(self.stud_university_choice[1])

        # Now check the score of student and university base point and then check available capacity in university
        if univ_choice1.univ_base_point <= self.stud_score: # it means student scores above univ base
            # Now check availability of s

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...