Unbounded Fractional Knapsack | Python implementation of the approach ; Function to return the maximum required value ; maxratio will store the maximum value to weight ratio we can have for any item and maxindex will store the index of that element ; Find the maximum ratio ; The item with the maximum value to weight ratio will be put into the knapsack repeatedly until full ; Driver code
import sys NEW_LINE def knapSack ( W , wt , val , n ) : NEW_LINE INDENT maxratio = - sys . maxsize - 1 ; NEW_LINE maxindex = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( ( val [ i ] / wt [ i ] ) > maxratio ) : NEW_LINE INDENT maxratio = ( val [ i ] / wt [ i ] ) ; NEW_LINE maxindex = i ; NEW_LINE DEDENT DEDENT return ( W * maxratio ) ; NEW_LINE DEDENT val = [ 14 , 27 , 44 , 19 ] ; NEW_LINE wt = [ 6 , 7 , 9 , 8 ] ; NEW_LINE n = len ( val ) ; NEW_LINE W = 50 ; NEW_LINE print ( knapSack ( W , wt , val , n ) ) ; NEW_LINE