MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / fractional_cover

Function fractional_cover

greedy_methods/fractional_cover_problem.py:33–93  ·  view source on GitHub ↗

Solve the Fractional Cover Problem. Args: items: A list of items, where each item has weight and value attributes. capacity: The maximum weight capacity of the knapsack. Returns: The maximum value that can be obtained by selecting fractions of items to cover

(items: list[Item], capacity: int)

Source from the content-addressed store, hash-verified

31
32
33def fractional_cover(items: list[Item], capacity: int) -> float:
34 """
35 Solve the Fractional Cover Problem.
36
37 Args:
38 items: A list of items, where each item has weight and value attributes.
39 capacity: The maximum weight capacity of the knapsack.
40
41 Returns:
42 The maximum value that can be obtained by selecting fractions of items to cover
43 the knapsack's capacity.
44
45 Raises:
46 ValueError: If capacity is negative.
47
48 Examples:
49 >>> fractional_cover((Item(10, 60), Item(20, 100), Item(30, 120)), capacity=50)
50 240.0
51
52 >>> fractional_cover([Item(20, 100), Item(30, 120), Item(10, 60)], capacity=25)
53 135.0
54
55 >>> fractional_cover([Item(10, 60), Item(20, 100), Item(30, 120)], capacity=60)
56 280.0
57
58 >>> fractional_cover(items=[Item(5, 30), Item(10, 60), Item(15, 90)], capacity=30)
59 180.0
60
61 >>> fractional_cover(items=[], capacity=50)
62 0.0
63
64 >>> fractional_cover(items=[Item(10, 60)], capacity=5)
65 30.0
66
67 >>> fractional_cover(items=[Item(10, 60)], capacity=1)
68 6.0
69
70 >>> fractional_cover(items=[Item(10, 60)], capacity=0)
71 0.0
72
73 >>> fractional_cover(items=[Item(10, 60)], capacity=-1)
74 Traceback (most recent call last):
75 ...
76 ValueError: Capacity cannot be negative
77 """
78 if capacity < 0:
79 raise ValueError("Capacity cannot be negative")
80
81 total_value = 0.0
82 remaining_capacity = capacity
83
84 # Sort the items by their value-to-weight ratio in descending order
85 for item in sorted(items, key=attrgetter("ratio"), reverse=True):
86 if remaining_capacity == 0:
87 break
88
89 weight_taken = min(item.weight, remaining_capacity)
90 total_value += weight_taken * item.ratio

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected