Advertisement
skb50bd

Fractional Knapsack Problem

Nov 3rd, 2016
260
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.38 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2.  
  3. '''
  4. Author: Shakib Haris
  5. Problem: Fractional Knapsack Problem
  6. Solution: Greedy Method
  7. Input: Number of Items, Knapsack Size/Weight, Items' Value and Weight
  8. Output: Items in the Knapsack, Total Value of the Items
  9. '''
  10.  
  11. class item:
  12.     def __init__ (self, ID, value, weight):
  13.         self.ID = ID
  14.         self.value = value
  15.         self.weight = weight
  16.         self.valueWeightRatio = value / weight
  17.         self.taken = 0.0
  18.  
  19.  
  20. def fillUpKnapsack (A, W):
  21.     for i in A:
  22.         if i.weight <= W:
  23.             i.taken = 1.0
  24.             W -= i.weight
  25.         else:
  26.             i.taken = W / i.weight
  27.             W = 0
  28.  
  29. def printKnapsack (A):
  30.     cost = 0.0
  31.  
  32.     for i in A:
  33.         if i.taken > 0.0:
  34.            print ("Item ", i.ID, ": Value ", i.taken * i.value, " Weight ", int (i.taken * i.weight), sep = "")
  35.            cost += i.taken * i.value
  36.     print ("Maximum Valuation: %d" %cost)
  37.  
  38.  
  39.  
  40. print ("Number of Items: ", end = "")
  41. N = int(input())
  42. print ("Knapsack Capacity: ", end = "")
  43. W = int(input())
  44.  
  45. A = []
  46. print ("Value Weight of: ")
  47. for i in range (N):
  48.     print ("Item ", i + 1, ": ", sep = "", end = "")
  49.     v, w = [int (x) for x in input().split()]
  50.     A.append(item(i + 1, v, w))
  51.  
  52. A.sort (key=lambda x: x.valueWeightRatio, reverse = True)
  53.  
  54. cost = fillUpKnapsack (A, W)
  55.  
  56. print ("\n\nKnapsack Properties: ")
  57. printKnapsack (A)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement