For problem set 8 does anyone have any advice on how to write the greedyAdvisor() function? I'm guessing you have to turn the dictionary of subjects into a list then sort it, but I can't figure out how to do this yet. If someone could share their code that would be cool.... Thanks.
Here is how i solved the greedyAdvisor() problem, I'd be interested to see how others did it... # # Problem 2: Subject Selection By Greedy Optimization # def greedyAdvisor(subjects, maxWork, comparator): subjects_dict = loadSubjects(subjects) rank_list = [] #1. Count the number of times each item in the subjects_dict is greater # than all the items in the list, based on the comparator function # passed in #2. Add the (count, subject key aka (item1)) as a tuple to the rank_list #3. Sort the rank_list from highest count to lowest for item1 in subjects_dict: count = 0 for item2 in subjects_dict: if comparator(subjects_dict[item1],subjects_dict[item2]): count = count + 1 rank_list.append((count,item1)) rank_list_sorted = sorted(rank_list, key=lambda rank_list: rank_list[0], reverse = True) #1. For every item in rank_list_sorted get the work value #2. Add the work value to the workload and save it to temp_workload #3. If temp_workload is less than or equal to maxWork # a. update workload to equal temp_workload # b. add the key and item from the subjects_dict to the output_dict #4. Else if the temp_workload is greater than maxWork set the temp_workload # back to the current workload value # # Variables explained: # i[1] = the subject key string --> example '15.01' # subjects_dict[i[1]][1] = the work value output_dict = {} workload = 0 temp_workload = 0 for i in rank_list_sorted: temp_workload = workload + subjects_dict[i[1]][1] if temp_workload <= maxWork: workload = temp_workload output_dict[i[1]]= subjects_dict[i[1]] else: temp_workload = workload printSubjects(output_dict)
Join our real-time social learning platform and learn together with your friends!