Repository where I mostly put random python scripts.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

51 lines
1.5 KiB

  1. """
  2. Jeffery Russell
  3. 12-1-18
  4. """
  5. def knapsack(V, W, capacity):
  6. """
  7. Dynamic programming implementation of the knapsack problem
  8. :param V: List of the values
  9. :param W: List of weights
  10. :param capacity: max capacity of knapsack
  11. :return: List of tuples of objects stolen in form (w, v)
  12. """
  13. choices = [[[] for i in range(capacity + 1)] for j in range(len(V) + 1)]
  14. cost = [[0 for i in range(capacity + 1)] for j in range(len(V) + 1)]
  15. for i in range(0, len(V)):
  16. for j in range(0, capacity + 1):
  17. if W[i] > j: # don't include another item
  18. cost[i][j] = cost[i -1][j]
  19. choices[i][j] = choices[i - 1][j]
  20. else: # Adding another item
  21. cost[i][j] = max(cost[i-1][j], cost[i-1][j - W[i]] + V[i])
  22. if cost[i][j] != cost[i-1][j]:
  23. choices[i][j] = choices[i - 1][j - W[i]] + [(W[i], V[i])]
  24. else:
  25. choices[i][j] = choices[i - 1][j]
  26. return choices[len(V) -1][capacity]
  27. def printSolution(S):
  28. """
  29. Takes the output of knapsack and prints it in a
  30. pretty format.
  31. :param S: list of tuples representing items stolen
  32. :return: None
  33. """
  34. print("Thief Took:")
  35. for i in S:
  36. print("Weight: " + str(i[0]) + "\tValue: \t" + str(i[1]))
  37. print()
  38. print("Total Value Stolen: " + str(sum(int(v[0]) for v in S)))
  39. print("Total Weight in knapsack: " + str(sum(int(v[1]) for v in S)))
  40. values = [99,1,1,1,1, 1,1]
  41. weights = [5,1,2,3,4,5,1]
  42. printSolution(knapsack(values, weights, 6))