Menu
CoddyTech

Finale: Registro delle scorte

Lezione 47 di 48 del corso Rust per sviluppatori Python di Coddy.

challenge icon

Sfida

Medio

Trasferisci l’intera implementazione di riferimento in Python nell’API Rust fornita. Le eccezioni Python diventano valori Rust Result espliciti; gli oggetti conservati nel dizionario diventano stato Rust posseduto. L’input contiene fino a 100 righe name delta; i nomi sono parole ASCII minuscole di al massimo 31 byte e i delta sono compresi tra -1000 e 1000. L’input vuoto è valido. Stock::new() -> Stock parte da zero; quantity(&self) -> i32 ne legge la quantità; apply(&mut self, delta: i32) -> Result<(), &'static str> rifiuta una quantità risultante negativa con Err("negative"), lasciando invariato lo stato. Ledger::new() -> Ledger parte vuoto; il suo apply(&mut self, name: &str, delta: i32) ha lo stesso contratto di risultato e non deve creare un elemento mancante in caso di rifiuto. quantity(&self, name: &str) -> Option<i32> distingue un elemento mancante da uno con quantità zero. report(&self) -> String elenca solo le scorte positive nel formato name:quantity, ordinate per nome e separate da nuove righe, oppure restituisce empty. Restituisci rejected:N, seguito dal resoconto nelle righe successive. Le chiamate a report non modificano lo stato. Il dizionario Python possiede riferimenti agli oggetti Stock; Rust dovrebbe possedere i nomi e i valori delle scorte in una mappa. Mantieni la distinzione tra un elemento mancante e un elemento con quantità zero.

Implementa le API esportate richieste e restituisci il risultato di exercise::solve(input: &str) -> String senza una nuova riga finale. Non stampare nel codice modificabile. Il driver bloccato verifica separatamente le API richieste, legge tutto lo stdin e stampa il testo restituito con una nuova riga finale.

Il tuo codice va inserito in exercise.rs, stock.rs, ledger.rs. main.rs contiene il codice di input/output fornito e non può essere modificato.

Implementazione di riferimento completa in Python per lo stesso contratto di input valido:

"""Python reference for the valid stock-ledger input contract."""
import sys


class Stock:
    def __init__(self):
        self._quantity = 0

    @property
    def quantity(self):
        return self._quantity

    def apply(self, delta):
        candidate = self._quantity + delta
        if candidate < 0:
            raise ValueError("negative")
        self._quantity = candidate


class Ledger:
    def __init__(self):
        self._items = {}

    def apply(self, name, delta):
        stock = self._items.get(name)
        if stock is None:
            stock = Stock()
            stock.apply(delta)
            self._items[name] = stock
        else:
            stock.apply(delta)

    def quantity(self, name):
        stock = self._items.get(name)
        return None if stock is None else stock.quantity

    def report(self):
        lines = [f"{name}:{stock.quantity}"
                 for name, stock in sorted(self._items.items())
                 if stock.quantity > 0]
        return "\n".join(lines) or "empty"


def solve(text):
    ledger = Ledger()
    rejected = 0
    tokens = iter(text.split())
    for name in tokens:
        delta = int(next(tokens))
        try:
            ledger.apply(name, delta)
        except ValueError:
            rejected += 1
    return f"rejected:{rejected}\n{ledger.report()}"


if __name__ == "__main__":
    print(solve(sys.stdin.read()))

Provalo tu

#![allow(dead_code, unused_imports, unused_variables, unused_mut)]
mod exercise;
mod stock;
mod ledger;
use std::io::{self, Read};
fn main() {
    let mut input=String::new();
    io::stdin().read_to_string(&mut input).unwrap();
    // INIZIO DELLE VERIFICHE DELL'API PUBBLICA
let mut s = stock::Stock::new(); assert_eq!(s.quantity(), 0);
    s.apply(11).unwrap(); assert_eq!(s.apply(-12), Err("negative")); assert_eq!(s.quantity(), 11);
    s.apply(-11).unwrap(); assert_eq!(s.quantity(), 0);
    let mut l = ledger::Ledger::new(); assert_eq!(l.quantity("held"), None);
    assert_eq!(l.apply("held", -8), Err("negative")); assert_eq!(l.quantity("held"), None);
    l.apply("held", 17).unwrap(); l.apply("alpha", 2).unwrap();
    assert_eq!(l.apply("held", -18), Err("negative")); assert_eq!(l.quantity("held"), Some(17));
    assert_eq!(l.report(), "alpha:2\nheld:17"); assert_eq!(l.report(), "alpha:2\nheld:17");
    l.apply("alpha", -2).unwrap(); assert_eq!(l.quantity("alpha"), Some(0)); assert_eq!(l.report(), "held:17");
    assert_eq!(ledger::Ledger::new().report(), "empty");
    // FINE DELLE VERIFICHE DELL'API PUBBLICA
    println!("{}", exercise::solve(&input));
}

Tutte le lezioni di Rust per sviluppatori Python

Esercitati da solo: Compilatore Rust online