Menu
CoddyTech

移植 Rust 库存管理系统

Coddy 面向 Rust 开发者的 Python 课程的第 47 课,共 48 课。

challenge icon

挑战

入门

请移植下面完整的 Rust 库存程序。在 inventory.py 中实现 inventory(lines)。它接收格式正确的 name amount 字符串,并返回不带末尾换行符的输出文本。名称由非空的小写 ASCII 字母组成;数量是有符号的十进制整数。累加每个名称的所有更新,包括中间的负数总计。聚合后,丢弃小于或等于零的总计。按名称升序返回正数对应的 name:total 条目,并用换行符连接;如果没有剩余条目,则返回 empty。此函数不要读取输入或打印内容。锁定的 driver.py 会读取一个非负数量和相应条数的记录,然后打印结果,并在末尾添加换行符。

Rust 参考实现使用 BTreeMap 保存名称,并通过 entry 修改条目。它使用小型有符号十进制类型,避免固定宽度整数溢出,且不依赖外部 crate。Python 的 int 可以替代这个辅助类型,sorted 则能提供 BTreeMap 所保证的排序。两个程序都会先聚合,再进行筛选。对于 pen 3、book 2、pen -1,返回 book:2,后接 pen:2。

use std::cmp::Ordering;
use std::collections::BTreeMap;
use std::io::{self, Read};
// Signed decimal arithmetic keeps the reference independent of integer width.
#[derive(Clone, Default)]
struct Decimal { negative: bool, digits: Vec<u8> }
impl Decimal {
    fn parse(text: &str) -> Self {
        let negative = text.starts_with('-');
        let raw = text.trim_start_matches(|c| c == '+' || c == '-');
        let mut value = Self { negative, digits: raw.bytes().rev().map(|b| b - b'0').collect() };
        value.normalize();
        value
    }
    fn normalize(&mut self) {
        while self.digits.last() == Some(&0) { self.digits.pop(); }
        if self.digits.is_empty() { self.negative = false; }
    }
    fn magnitude_cmp(&self, other: &Self) -> Ordering {
        self.digits.len().cmp(&other.digits.len())
            .then_with(|| self.digits.iter().rev().cmp(other.digits.iter().rev()))
    }
    fn add(&mut self, other: &Self) {
        if self.negative == other.negative {
            let length = self.digits.len().max(other.digits.len());
            self.digits.resize(length, 0);
            let mut carry = 0;
            for i in 0..length {
                let sum = self.digits[i] + other.digits.get(i).copied().unwrap_or(0) + carry;
                self.digits[i] = sum % 10;
                carry = sum / 10;
            }
            if carry != 0 { self.digits.push(carry); }
        } else {
            if self.magnitude_cmp(other) == Ordering::Less {
                let old = self.clone();
                *self = other.clone();
                self.subtract_magnitude(&old);
            } else { self.subtract_magnitude(other); }
        }
        self.normalize();
    }
    // Precondition: self has at least the magnitude of other.
    fn subtract_magnitude(&mut self, other: &Self) {
        let mut borrow: i16 = 0;
        for i in 0..self.digits.len() {
            let mut difference = self.digits[i] as i16
                - other.digits.get(i).copied().unwrap_or(0) as i16 - borrow;
            borrow = if difference < 0 { 1 } else { 0 };
            if difference < 0 { difference += 10; }
            self.digits[i] = difference as u8;
        }
    }
    fn positive(&self) -> bool { !self.negative && !self.digits.is_empty() }
    fn positive_text(&self) -> String {
        self.digits.iter().rev().map(|d| (b'0' + d) as char).collect()
    }
}
fn main() {
    let mut input = String::new();
    io::stdin().read_to_string(&mut input).expect("read input");
    let mut lines = input.lines();
    let count: usize = lines.next().expect("count").parse().expect("nonnegative count");
    let mut stock: BTreeMap<String, Decimal> = BTreeMap::new();
    for line in lines.take(count) {
        let mut fields = line.split_whitespace();
        let name = fields.next().expect("name").to_owned();
        let amount = Decimal::parse(fields.next().expect("amount"));
        stock.entry(name).or_default().add(&amount);
    }
    let output: Vec<String> = stock.iter().filter(|(_, v)| v.positive())
        .map(|(k, v)| format!("{}:{}", k, v.positive_text())).collect();
    println!("{}", if output.is_empty() { String::from("empty") } else { output.join("\n") });
}

请将你的代码写在 inventory.py 中。锁定的 driver.py 负责提供输入和输出,不能编辑。

亲手试试

from inventory import inventory

lines = [input() for _ in range(int(input()))]
print(inventory(lines))

面向 Rust 开发者的 Python中的所有课

自己练习: Python 在线编译器