Files
CS412-Applied-Algorithms/Greedy-Algorithms/cs412_knapsack_fractional.py

79 lines
2.0 KiB
Python

"""
name: Nicholas Tamassia
Honor Code and Acknowledgments:
This work complies with the JMU Honor Code.
Comments here on your code and submission.
"""
from dataclasses import dataclass
from typing import Self, override
# I don't like tuples, dataclasses ftw
@dataclass(frozen=True)
class KnapsackItem:
name: str
value: float
weight: float
@property
def value_ratio(self) -> float:
return self.value / self.weight
@override
def __str__(self) -> str:
return f"{self.name}({self.value:.2f}, {self.weight:.2f})"
@classmethod
def parse(cls, string: str) -> Self:
values: list[str] = string.strip().split()
name, value, weight = values[0], float(values[1]), float(values[2])
return cls(name, value, weight)
def knapsack(
capacity: int, items: list[KnapsackItem]
) -> tuple[list[KnapsackItem], float]:
current_capacity: float = float(capacity)
sorted_items: list[KnapsackItem] = sorted(items, key=lambda i: -i.value_ratio)
total_value: float = 0.0
fractional_items: list[KnapsackItem] = []
for item in sorted_items:
if abs(current_capacity) < 1e-8:
break
name, value, weight = item.name, item.value, item.weight
if current_capacity < weight:
value = item.value_ratio * current_capacity
weight = current_capacity
fractional_items.append(KnapsackItem(name, value, weight))
total_value += value
current_capacity -= weight
return fractional_items, total_value
# All modules for CS 412 must include a main method that allows it
# to imported and invoked from other python scripts
def main():
capacity: int = int(input())
n: int = int(input())
items: list[KnapsackItem] = [KnapsackItem.parse(input()) for _ in range(0, n)]
fractional_items, total_value = knapsack(capacity, items)
print(" ".join(map(str, fractional_items)))
print(total_value)
if __name__ == "__main__":
main()