Professional Documents
Culture Documents
DAA Lab No.1.Ipynb - Colaboratory
DAA Lab No.1.Ipynb - Colaboratory
ipynb - Colaboratory
Reg No : URK20CS2099
Ex. No:1
Date : 15/12/2021
Aim:
To implement greedy technique to find the optimal solution for the fractional knapsack problem.
Algorithm:
Step2: Itrate the number of fot in the list and append to the list internally.
Step4: Using for loop if weight is less then capacity add max value with itration of value and
decrease the capicity by weight and append the fraciont by 1.
Step5:return the max value.give the input and print the function.
Program:
def knapsack (W, weight, value):
ratios = [v/w for v,w in zip(value, weight)]
n= len(weight)
index = list(range(n))
index.sort(key=lambda i: ratios[i], reverse= True)
max_value = 0
fractions = [0]*n
for i in index:
if weight[i] <= W :
max_value += value[i]
W -= weight[i]
fractions[i] = 1
else:
fractions[i] = W/weight[i]
max_value += value[i] * fractions[i]
break
print(fractions)
return max_value
weight = [10, 20, 30]
value = [60, 100, 120]
W=50
print(knapsack(W, weight, value))
[1, 1, 0.6666666666666666]
240.0
https://colab.research.google.com/drive/1xaDSF4g-O_38coN2-TW7Oqu10Ovk9lRQ?usp=sharing#scrollTo=5M3K5PJjY25N&printMode=true 1/2
12/16/21, 12:00 AM DAA Lab Report Format.ipynb - Colaboratory
https://colab.research.google.com/drive/1xaDSF4g-O_38coN2-TW7Oqu10Ovk9lRQ?usp=sharing#scrollTo=5M3K5PJjY25N&printMode=true 2/2