0% found this document useful (0 votes)
13 views6 pages

Assignment

Uploaded by

Mani Raj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views6 pages

Assignment

Uploaded by

Mani Raj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

Assignment -1

18CSC207T- Competitive Professional skills


111
Krupasai Shetty(RA21113040017)
ManiRaj(RA211103040062)
Devansh Singh(RA21110030040113)

Fractional knapsack problem (greedy


algorithm to solve the fractional knapsack)
Introduction

The fractional knapsack problem:

1. Fractional Knapsack vs. 0/1 Knapsack: In the fractional


knapsack problem, items can be divided into fractions, allowing
for more flexible solutions. This is different from the 0/1
knapsack problem, where items must be either taken entirely or
not at all.
2. Greedy Strategy: The fractional knapsack problem is often
solved using a greedy strategy, where items are sorted based on
their value-to-weight ratios in decreasing order. This strategy
ensures that the most valuable items per unit weight are
considered first, leading to an optimal or near-optimal solution.
3.Optimality of Greedy Approach: Unlike the 0/1 knapsack
problem, where the greedy approach may not always yield the
optimal solution, the greedy approach for the fractional
knapsack problem typically provides the optimal solution. This
is because fractional knapsack's flexibility allows for maximizing
value without strict constraints on item selection.

The greedy algorithm works in action for


the fractional knapsack problem:

1. Sorting by Value-to-Weight Ratio: Initially, the algorithm sorts


the items based on their value-to-weight ratios in decreasing
order. This sorting step ensures that the most valuable items
per unit weight are considered first.
2. Iterative Selection: Starting with an empty knapsack, the
algorithm iteratively selects items to include in the knapsack.
For each item in the sorted list, it checks if adding the entire
item will exceed the knapsack's capacity. If it does not, the
entire item is added to the knapsack. If adding the entire item
would exceed the capacity, a fraction of the item is added to fill
the remaining space in the knapsack.
3. Optimal Solution: By following this greedy strategy of
selecting items with the highestvalue-to-weight ratios first and
adding fractional parts when necessary, the algorithm
maximizes the total value that can be carried in the knapsack
without violating the weight constraint. This approach typically
leads to an optimal or near-optimal solution for the fractional
knapsack problem.

CODE:
class Item:
def _init_(self, weight, value):
self.weight = weight
self.value = value
self.cost = value / weight

def fractional_knapsack(items, capacity):


items.sort(key=lambda x: x.cost, reverse=True)
total_value = 0
knapsack = []
for item in items:
if capacity >= item.weight:
knapsack.append((item.weight, item.value))
total_value += item.value
capacity -= item.weight
else:
fraction = capacity / item.weight
knapsack.append((item.weight * fraction, item.value *
fraction))
total_value += item.value * fraction
break

return knapsack, total_value

def main():
n = int(input("Enter the number of items: "))
items = []
for _ in range(n):
weight, value = map(int, input("Enter weight and value of
item {}: ".format(_+1)).split())
items.append(Item(weight, value))
capacity = int(input("Enter the capacity of knapsack: "))

result, total_value = fractional_knapsack(items, capacity)


print("Items in knapsack and their fractions:")
for item in result:
print("Weight: {}, Value: {}".format(item[0], item[1]))
print("Total value in knapsack:", total_value)

if _name_ == "_main_":
main()

OUTPUT:
𝐒𝐭𝐚𝐧𝐝𝐚𝐫𝐝 𝐢𝐧𝐩𝐮𝐭
Enter the number of items: 3
Enter weight and value of item 1: 10 60
Enter weight and value of item 2: 20 100
Enter weight and value of item 3: 30 120
Enter the capacity of knapsack: 50
𝐒𝐭𝐚𝐧𝐝𝐚𝐫𝐝 𝐨𝐮𝐭𝐩𝐮𝐭
Items in knapsack and their fractions:
Weight: 10.0, Value: 60.0
Weight: 20.0, Value: 100.0
Weight: 20.0, Value: 60.0
Total value in knapsack: 220.0

The fractional knapsack problem has several


real-world applications across different
domains.

The fractional knapsack problem finds applications in resource


allocation for manufacturing, optimizing investment portfolios
in finance, data compression algorithms in computer science,
and even in tasks like optimizing load distribution in
transportation logistics. Its flexibility in handling fractional items
makes it a powerful tool for various optimization problems in
real-world scenarios.

You might also like