Advertisement
dbwonders

ps8_greedy

May 14th, 2012
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.69 KB | None | 0 0
  1. def greedyAdvisor(subjects, maxWork, comparator):
  2.     """
  3.    Returns a dictionary mapping subject name to (value, work) which includes
  4.    subjects selected by the algorithm, such that the total ***work*** of subjects in
  5.    the dictionary is not greater than maxWork.  The subjects are chosen using
  6.    a greedy algorithm.  The subjects dictionary should not be mutated.
  7.  
  8.    subjects: dictionary mapping subject name to (value, work)
  9.    maxWork: int >= 0
  10.    comparator: function taking two tuples and returning a bool
  11.    returns: dictionary mapping subject name to (value, work)
  12.    """
  13.    
  14.     greedy_dict = {}
  15.     greedy_list = []
  16.     temp = ()
  17.     work_total = 0
  18.     sub_list = subjects.items() #[(subject,(value,work),(subject,(value,work))...]
  19.    
  20.  
  21.     while work_total < maxWork:
  22.         # bubble search
  23.         for i in range(len(sub_list)-1):            
  24.             if comparator(sub_list[i][1], sub_list[i+1][1])==True:
  25.                 temp = sub_list[i]
  26.                 sub_list[i] = sub_list[i+1]
  27.                 sub_list[i + 1] = temp          
  28.         if sub_list[0]==sub_list[-1]: #if options run out
  29.             print 'note: maximum work load exceeds possible work'
  30.             greedy_list.append(sub_list[-1])
  31.             break
  32.         elif work_total + sub_list[-1][1][WORK] <= maxWork:
  33.             work_total += sub_list[-1][1][WORK]
  34.             greedy_list.append(sub_list.pop()) # take the course
  35.         else:
  36.             sub_list.pop() # do not take course
  37.     # create dictionary from list        
  38.     for j in range(len(greedy_list)):
  39.         greedy_dict[greedy_list[j][0]] = greedy_list[j][1]
  40.  
  41.     return greedy_dict
  42.      
  43.     #printSubjects(greedy_dict)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement