Advertisement
amu2002

fractional_knapsack

Nov 20th, 2023 (edited)
37
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.61 KB | None | 0 0
  1. n = int(input("Enter the number of items: "))
  2. maxwt = int(input("Maximum weight: "))
  3. profit = list(map(int, input("Enter profit value of items: ").split()))
  4. weight = list(map(int, input("Enter weight of items: ").split()))
  5.  
  6. wt = 0
  7. max_profit = 0
  8.  
  9. ppw = []
  10. for i in range(n):
  11.     ppw.append(profit[i] / weight[i])
  12.  
  13. order = []  
  14. for i in range(n):
  15.     order.append(ppw.index(max(ppw)))
  16.     ppw[ppw.index(max(ppw))] = 0
  17.  
  18. i = 0
  19.  
  20. print("\nItems in Knapsack:")
  21. print("Item\tWeight\tProfit Value\tFraction")
  22.  
  23. while wt != maxwt and i < n:
  24.     if (wt + weight[order[i]]) <= maxwt:
  25.         max_profit += profit[order[i]]
  26.         wt += weight[order[i]]
  27.         print("%d\t\t%d\t\t%d\t\t\t\t1" % (order[i] + 1, weight[order[i]], profit[order[i]]))
  28.     else:
  29.         fraction = (maxwt - wt) / weight[order[i]]
  30.         value = profit[order[i]] * fraction
  31.         max_profit += value
  32.         wt = maxwt
  33.         print("%d\t\t%d\t\t%0.2f\t\t\t\t%0.2f" % (order[i] + 1, weight[order[i]], value, fraction))
  34.     i += 1
  35.  
  36. print("\nMaximum profit = %0.2f" % max_profit)
  37.  
  38. """
  39. Enter the number of items: 5
  40. Maximum weight: 10
  41. Enter profit value of items: 10 15 10 12 8
  42. Enter weight of items: 3 3 2 5 1
  43.  
  44. Items in Knapsack:
  45. Item    Weight  Profit Value    Fraction
  46. 5               1               8                               1
  47. 2               3               15                              1
  48. 3               2               10                              1
  49. 1               3               10                              1
  50. 4               5               2.40                            0.20
  51.  
  52. Maximum profit = 45.40
  53. """
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement