Programmazione competitivaFacile

Zaino frazionario

Guida dettagliata e implementazione Python per il problema dello "Zaino frazionario".

Dichiarazione del problema

Facile

Scrivi una funzione fractional_knapsack(W, items) che prende la capacità dello zaino W e un elenco di tuple items dove ogni tupla è (value, weight). Trova il valore totale massimo ottenibile nello zaino, consentendo la rottura/frazionamento degli oggetti. Arrotondare l'output a 2 cifre decimali.

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

Esempi

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?
Prendi in considerazione l'utilizzo di strutture dati specifiche di Greedy come set o heap.
Edge Cases to Watch
  • Strutture di input vuote
  • Ingressi a elemento singolo
  • Grandi limiti numerici

Pronto a risolvere?

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

Apri nell'editor
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

Risorse Python consigliate

Espandi le tue conoscenze con tutorial interattivi, foglietti illustrativi e confronti di codici correlati.