Skip to content

another method for fractional knapsack.py #12076

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions greedy_methods/fractional knapsack.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
def greedy_knapsack(n, w, p, m):

Check failure on line 1 in greedy_methods/fractional knapsack.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (N999)

greedy_methods/fractional knapsack.py:1:1: N999 Invalid module name: 'fractional knapsack'
ratio = [0] * n

# Calculate the ratio of profit/weight
for i in range(n):
ratio[i] = p[i] / w[i]

# Sort items by their ratio (profit/weight)
items = sorted(range(n), key=lambda i: ratio[i], reverse=True)

current_weight = 0
max_profit = 0.0
x = [0] * n

for i in items:
if current_weight + w[i] <= m:
x[i] = 1 # Take the whole item
current_weight += w[i]
max_profit += p[i]
else:
x[i] = (m - current_weight) / w[i] # Take the fractional part
max_profit += x[i] * p[i]
break

print(f"Optimal solution for greedy method: {max_profit:.2f}")
print("Solution vector for greedy method:", x)


if __name__ == "__main__":
n = int(input("Enter number of objects: "))
w = list(map(int, input("Enter the object weights: ").split()))
p = list(map(int, input("Enter the profit: ").split()))
m = int(input("Enter maximum capacity: "))

greedy_knapsack(n, w, p, m)
Loading