Fractional Knapsack in Python I wrote this in order to solve the fractional knapsack problem. Any feedback is appreciated.

def get_optimal_value(capacity, weights, values):
    value = 0.
    if sum(weights) &lt;= capacity:
        return sum(values)
    if len(weights) == 1:
        value = values[0]/float(weights[0])*capacity
    densities = [(v/float(w), w) for (v,w) in zip(values, weights)]
    densities = sorted(densities, key=lambda density:density[0], reverse=True)
    fraction = 0.
    #print(densities)
    for i in range(len(weights)):
        fraction = sum([f for (d,f) in densities[0:i]])
        #print(i, fraction, capacity)
        if fraction &gt;capacity and i &gt;0:
            value = sum([d*f for (d,f) in densities[0:i-1]]) + densities[i][0]*(1.0000000-densities[i][1]/float(capacity))*capacity
        if fraction == capacity and i &gt;0:
            value = sum([d*f for (d,f) in densities[0:i]])

    return value
The program does not solve the problem:

&gt;&gt;&gt; get_optimal_value(1, (1, 1, 1, 1), (1, 1, 1, 1))
2.0


Here we have a knapsack with capacity 1, and four kinds of item, each with weight 1 and value 1. So all ways of filling the knapsack have value 1.