1+ # https://en.wikipedia.org/wiki/Continuous_knapsack_problem
2+ # https://www.guru99.com/fractional-knapsack-problem-greedy.html
3+ # https://medium.com/walkinthecode/greedy-algorithm-fractional-knapsack-problem-9aba1daecc93
4+
5+ """
6+ Author : Anubhav Sharma
7+ This is a pure Python implementation of Dynamic Programming solution to the Fractional Knapsack of a given items and weights.
8+ The problem is :
9+ Given N items and weights, to find the max weight of item to put in fractional knapsack in that given knapsack and
10+ return it.
11+ Example: Weight of knapsack to carry, Items and there weights as input will return
12+ Items in fraction to put in the knapsack as per weight as output
13+ """
14+
15+ def fractional_knapsack (value : list [int ], weight : list [int ], capacity : int ) -> tuple [int , list [int ]]:
16+ """
17+ >>> value = [1, 3, 5, 7, 9]
18+ >>> weight = [0.9, 0.7, 0.5, 0.3, 0.1]
19+ >>> fractional_knapsack(value, weight, 5)
20+ (25, [1, 1, 1, 1, 1])
21+ >>> fractional_knapsack(value, weight, 15)
22+ (25, [1, 1, 1, 1, 1])
23+ >>> fractional_knapsack(value, weight, 25)
24+ (25, [1, 1, 1, 1, 1])
25+ >>> fractional_knapsack(value, weight, 26)
26+ (25, [1, 1, 1, 1, 1])
27+ >>> fractional_knapsack(value, weight, -1)
28+ (-90.0, [0, 0, 0, 0, -10.0])
29+ >>> fractional_knapsack([1, 3, 5, 7], weight, 30)
30+ (16, [1, 1, 1, 1])
31+ >>> fractional_knapsack(value, [0.9, 0.7, 0.5, 0.3, 0.1], 30)
32+ (25, [1, 1, 1, 1, 1])
33+ >>> fractional_knapsack([], [], 30)
34+ (0, [])
35+ """
36+ index = list (range (len (value )))
37+ ratio = [v / w for v , w in zip (value , weight )]
38+ index .sort (key = lambda i : ratio [i ], reverse = True )
39+
40+ max_value = 0
41+ fractions = [0 ] * len (value )
42+ for i in index :
43+ if weight [i ] <= capacity :
44+ fractions [i ] = 1
45+ max_value += value [i ]
46+ capacity -= weight [i ]
47+ else :
48+ fractions [i ] = capacity / weight [i ]
49+ max_value += value [i ] * capacity / weight [i ]
50+ break
51+
52+ return max_value , fractions
53+
54+
55+ if __name__ == "__main__" :
56+ n = int (input ("Enter number of items: " ))
57+ value = input (f"Enter the values of the { n } item(s) in order: " ).split ()
58+ value = [int (v ) for v in value ]
59+ weight = input (f"Enter the positive weights of the { n } item(s) in order: " .split ())
60+ weight = [int (w ) for w in weight ]
61+ capacity = int (input ("Enter maximum weight: " ))
62+
63+ max_value , fractions = fractional_knapsack (value , weight , capacity )
64+ print ("The maximum value of items that can be carried:" , max_value )
65+ print ("The fractions in which the items should be taken:" , fractions )
66+
67+
0 commit comments