Advertisement
Guest User

Untitled

a guest
May 5th, 2016
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.98 KB | None | 0 0
  1. #!/bin/env python3
  2.  
  3. # Assignment 3.3
  4. # Group 7
  5. # Tobias Schramm & Malte Hansen
  6.  
  7. import sys
  8.  
  9. # Just a simple container to avoid messing around with too many arrays
  10. class Lecture():
  11. def __init__(self, cost, effort):
  12. self.cost = cost
  13. self.effort = effort
  14.  
  15. budget = 20
  16. lectures = [Lecture(1, 1), Lecture(2, 1), Lecture(1, 5), Lecture(7, 8), Lecture(3, 7), Lecture(5, 21), Lecture(1, 2), Lecture(4, 4), Lecture(5, 6)]
  17.  
  18. print('Number of items: {0}'.format(len(lectures)))
  19.  
  20. # Calculate maximum effort and cost
  21. max_effort = 0
  22. max_cost = 0
  23. for l in lectures:
  24. max_effort += l.effort
  25. max_cost += l.cost
  26. print('Maximum possible effort: {0}'.format(max_effort))
  27. print('Maximum possible cost: {0}'.format(max_cost))
  28.  
  29. # Create and init matrix
  30. M = [[0 for i in range(max_cost + 1)] for j in range(len(lectures))] # Fills matrix with zeroes
  31. for cost in range(1, max_cost + 1): # for i from 1 to max_cost + 1
  32. if lectures[0].cost != cost:
  33. M[0][cost] = max_effort + 1 # Let's use max_effort + 1 as our invalid value
  34. else:
  35. M[0][cost] = lectures[0].cost
  36.  
  37. # Fill it!
  38. for i in range(1, len(lectures)):
  39. lecture = lectures[i]
  40. for cost in range(1, max_cost + 1):
  41. if cost < lecture.cost:
  42. M[i][cost] = M[i - 1][cost]
  43. else:
  44. if M[i - 1][cost - lecture.cost] + lecture.effort > M[i - 1][cost]:
  45. M[i][cost] = M[i - 1][cost]
  46. else:
  47. M[i][cost] = M[i - 1][cost - lecture.cost] + lecture.effort
  48.  
  49. # Show the matrix because it's pretty
  50. print('ADS ', end='')
  51. for i in range(len(lectures)):
  52. print('{:3d} '.format(i), end='')
  53. print()
  54. for j in range(max_cost + 1):
  55. print('{:3d} '.format(j), end='')
  56. for i in range(len(lectures)):
  57. print('{:3d} '.format(M[i][j]), end='')
  58. print()
  59.  
  60. # Get the smallest amount of effort necessary to use all budget
  61. min_effort = max_effort + 1
  62. actual_cost = -1
  63. for cost in reversed(range(budget, max_cost)):
  64. effort = M[len(lectures) - 1][cost]
  65. if effort < min_effort:
  66. min_effort = effort
  67. actual_cost = cost
  68.  
  69. print('Best we can do is an effort of {0} spending {1}'.format(min_effort, actual_cost))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement