You are on page 1of 2

12/16/21, 12:00 AM DAA Lab Report Format.

ipynb - Colaboratory

Reg No : URK20CS2099

Ex. No:1

Date : 15/12/2021

Name :Glimpson Gidhi

Link : Video link


*https://youtu.be/bGcJ910nk_8 *

Aim:

To implement greedy technique to find the optimal solution for the fractional knapsack problem.

Algorithm:

Step1: Compute the ratio of weight and value.

Step2: Itrate the number of fot in the list and append to the list internally.

Step3: Sort the index based on ratio.Initlize the max value as 0.

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

Output:The program run succesfully and the output has come.

check 0s completed at 11:58 PM

https://colab.research.google.com/drive/1xaDSF4g-O_38coN2-TW7Oqu10Ovk9lRQ?usp=sharing#scrollTo=5M3K5PJjY25N&printMode=true 2/2

You might also like