|
| 1 | +def fractional_knapsack(items, capacity): |
| 2 | + # Calculate the value-to-weight ratio for each item |
| 3 | + for item in items: |
| 4 | + item['value_per_weight'] = item['value'] / item['weight'] |
| 5 | + |
| 6 | + # Sort items in non-increasing order of value-to-weight ratio |
| 7 | + items.sort(key=lambda x: x['value_per_weight'], reverse=True) |
| 8 | + |
| 9 | + total_value = 0 |
| 10 | + knapsack = [] |
| 11 | + |
| 12 | + for item in items: |
| 13 | + if item['weight'] <= capacity: |
| 14 | + total_value += item['value'] |
| 15 | + knapsack.append(item) |
| 16 | + capacity -= item['weight'] |
| 17 | + else: |
| 18 | + fraction = capacity / item['weight'] |
| 19 | + total_value += fraction * item['value'] |
| 20 | + knapsack.append({'item': item['item'], 'weight': item['weight']*fraction, 'value': item['value']*fraction}) |
| 21 | + break |
| 22 | + |
| 23 | + return total_value, knapsack |
| 24 | + |
| 25 | + |
| 26 | +# Example Usage |
| 27 | +items = [ |
| 28 | + {'item': 'Item 1', 'weight': 10, 'value': 60}, |
| 29 | + {'item': 'Item 2', 'weight': 20, 'value': 100}, |
| 30 | + {'item': 'Item 3', 'weight': 30, 'value': 120}, |
| 31 | +] |
| 32 | + |
| 33 | +capacity = 50 |
| 34 | + |
| 35 | +total_value, knapsack_items = fractional_knapsack(items, capacity) |
| 36 | + |
| 37 | +print(f'Total value in the knapsack: {total_value}') |
| 38 | +print('Selected items:') |
| 39 | +for item in knapsack_items: |
| 40 | + print(f"Item: {item['item']}, Weight: {item['weight']}, Value: {item['value']}") |
0 commit comments