Advertisement
dbwonders

dpAdvisorRevised

May 29th, 2012
50
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.82 KB | None | 0 0
  1. #'DP memo[(i, subsetWork)]'  based on brute force
  2. #
  3. def dpAdvisor(subjects, maxWork):
  4.     """
  5.    Returns a dictionary mapping subject name to (value, work), which
  6.    represents the globally optimal selection of subjects using a brute force
  7.    algorithm.
  8.  
  9.    subjects: dictionary mapping subject name to (value, work)
  10.    maxWork: int >= 0
  11.    returns: dictionary mapping subject name to (value, work)
  12.    """
  13.     nameList = subjects.keys()
  14.     tupleList = subjects.values()
  15.     bestSubset, bestSubsetValue = \
  16.             dpAdvisorHelper(tupleList, maxWork, 0, 0, {})
  17.     outputSubjects = {}
  18.     print bestSubset, bestSubsetValue
  19.     for i in bestSubset:
  20.         outputSubjects[nameList[i]] = tupleList[i]
  21.     return outputSubjects                          
  22.  
  23. def dpAdvisorHelper(subjects, maxWork, i, subsetWork, memo):    
  24.     try: return memo[(i, subsetWork)]
  25.     except KeyError:
  26.         # Hit the end of the list.
  27.         if i >= len(subjects):
  28.             memo[(i, subsetWork)]=[],0
  29.             return [],0
  30.         s = subjects[i]
  31.         withoutlist, withoutvalue = dpAdvisorHelper(subjects,maxWork, i+1, subsetWork, memo)
  32.         if subsetWork + s[WORK] > maxWork:
  33.             memo[(i, subsetWork)]=withoutlist,withoutvalue
  34.             return memo[(i, subsetWork)]
  35.         else:
  36.             withlist, withvalue = dpAdvisorHelper(subjects, maxWork, i+1, subsetWork + s[WORK], memo)
  37.             withlist = [i] + withlist
  38.             withvalue += s[VALUE]
  39.             #withoutlist, withoutvalue = dpAdvisorHelper(subjects,maxWork, i+1, subsetWork, memo)
  40.         if withvalue > withoutvalue:
  41.             memo[(i, subsetWork)]= withlist, withvalue
  42.             return memo[(i, subsetWork)]
  43.         else:  
  44.             memo[(i, subsetWork)] = withoutlist, withoutvalue
  45.             return memo[(i, subsetWork)]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement