Skip to content

Commit 53a946f

Browse files
Merge pull request #1 from Niladitya-coder/Niladitya-coder-patch-1
Create Fractional Knapsack.py
2 parents 5799376 + c41f1df commit 53a946f

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

Fractional Knapsack.py

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
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

Comments
 (0)