Advertisement
vaboro

dpAdvisorHelper

Aug 9th, 2012
42
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.10 KB | None | 0 0
  1. #            index   value work
  2. # tupleList = 0    [ (16,   8),
  3. #             1      ( 7,   7),
  4. #             2      ( 5,   3),
  5. #             3      ( 9,   6) ]
  6. #
  7. #            index   subject
  8. # nameList =  0    [ '6.00',
  9. #             1      '1.00',
  10. #             2      '6.01',
  11. #             3      '15.01' ]
  12. #
  13.  
  14. def dpAdvisor(subjects, maxWork):
  15.     """
  16.    Returns a dictionary mapping subject name to (value, work) that contains a
  17.    set of subjects that provides the maximum value without exceeding maxWork.
  18.  
  19.    subjects: dictionary mapping subject name to (value, work)
  20.    maxWork: int >= 0
  21.    returns: dictionary mapping subject name to (value, work)
  22.    """
  23.    
  24.     nameList = subjects.keys()
  25.     tupleList = subjects.values()
  26.     memo = {}
  27.     return dpAdvisorHelper(tupleList, len(tupleList)-1, maxWork, memo)
  28.  
  29. def dpAdvisorHelper(subjects, index, availableWork, memo):
  30.     """
  31.    Returns maximum value obtainable from available subjects with availableWork
  32.    constraint
  33.    
  34.    subjects: list containing (value, work) tuples
  35.    index: int >=0 and is the length of subjects list
  36.    availableWork: int and is the workload constraint
  37.    memo: dictionary mapping (index, availableWork) to subjects[index][VALUE]
  38.    """
  39.    
  40.     try: return memo[(index, availableWork)]
  41.     except KeyError:
  42.         if index == 0:
  43.             if subjects[index][WORK] <= availableWork:
  44.                 memo[(index, availableWork)] = subjects[index][VALUE]
  45.                 return subjects[index][VALUE]
  46.             else:
  47.                 memo[(index, availableWork)] = 0
  48.                 return 0
  49.         without_index = dpAdvisorHelper(subjects, index-1, availableWork, memo)
  50.         if subjects[index][WORK] > availableWork:
  51.             memo[(index, availableWork)] = without_index
  52.             return without_index
  53.         else:
  54.             with_index = subjects[index][VALUE] + dpAdvisorHelper(subjects,
  55.                         index-1, availableWork - subjects[index][WORK], memo)
  56.         res = max(with_index, without_index)
  57.         memo[(index, availableWork)] = res
  58.         return res
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement