Skip to content

Commit b6f9681

Browse files
authored
fractional knapsack.py
1 parent 03a4251 commit b6f9681

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

knapsack/fractional knapsack.py

+35
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
def greedy_knapsack(n, w, p, m):
2+
ratio = [0] * n
3+
4+
# Calculate the ratio of profit/weight
5+
for i in range(n):
6+
ratio[i] = p[i] / w[i]
7+
8+
# Sort items by their ratio (profit/weight)
9+
items = sorted(range(n), key=lambda i: ratio[i], reverse=True)
10+
11+
current_weight = 0
12+
max_profit = 0.0
13+
x = [0] * n
14+
15+
for i in items:
16+
if current_weight + w[i] <= m:
17+
x[i] = 1 # Take the whole item
18+
current_weight += w[i]
19+
max_profit += p[i]
20+
else:
21+
x[i] = (m - current_weight) / w[i] # Take the fractional part
22+
max_profit += x[i] * p[i]
23+
break
24+
25+
print(f"Optimal solution for greedy method: {max_profit:.2f}")
26+
print("Solution vector for greedy method:", x)
27+
28+
29+
if __name__ == "__main__":
30+
n = int(input("Enter number of objects: "))
31+
w = list(map(int, input("Enter the object weights: ").split()))
32+
p = list(map(int, input("Enter the profit: ").split()))
33+
m = int(input("Enter maximum capacity: "))
34+
35+
greedy_knapsack(n, w, p, m)

0 commit comments

Comments
 (0)