Wettbewerbsfähige ProgrammierungEinfach

Fraktionaler Rucksack

Detaillierte Anleitung und Python-Implementierung für das „Fractional Knapsack“-Problem.

Problemstellung

Einfach

Schreiben Sie eine Funktion fractional_knapsack(W, items), die die Rucksackkapazität W und eine Liste von Tupeln items übernimmt, wobei jedes Tupel (value, weight) ist. Finden Sie den maximal erreichbaren Gesamtwert im Rucksack, sodass Gegenstände zerbrochen/fraktioniert werden können. Runden Sie die Ausgabe auf zwei Dezimalstellen.

Einschränkungen
  • 1 <= len(items) <= 1000
  • 1 <= W <= 10^5
  • 1 <= value, weight <= 10^4

Beispiele

Example 1
Input
fractional_knapsack(50, [(60, 10), (100, 20), (120, 30)])
Output
240.0
Explanation

Take the first and second item fully, and 2/3 of the third item. Total value: 60 + 100 + 120 * (20/30) = 240.0.

Example 2
Input
fractional_knapsack(15, [(24, 10), (18, 10), (15, 10)])
Output
33.0
Explanation

Take the first item fully, and 1/2 of the second item. Total value: 24 + 18 * 0.5 = 33.0.

Need a Hint?
Erwägen Sie die Verwendung von Greedy-spezifischen Datenstrukturen wie Sets oder Heaps.
Edge Cases to Watch
  • Leere Eingabestrukturen
  • Einzelelementeingaben
  • Große numerische Grenzen

Bereit zur Lösung?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

Im Editor öffnen
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

Empfohlene Python-Ressourcen

Erweitern Sie Ihr Wissen mit zugehörigen interaktiven Tutorials, Spickzetteln und Codevergleichen.