Menu
CoddyTech

移植 C++ 库存系统

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

challenge icon

挑战

入门

移植下方完整的 C++17 库存管理程序。在 inventory.py 中实现 inventory(lines);它接收格式良好的 name amount 字符串,并返回不带末尾换行符的输出文本。名称是非空小写 ASCII 字母,数量是有符号十进制整数。按名称累加每次更新,包括负的中间总数。聚合后,舍弃小于或等于零的总数。按名称升序排列返回正数的 name:total 条目,并用换行符连接;如果没有剩余条目,则返回 empty。不要在此函数中读取输入或打印内容。被锁定的 driver.py 会读取一个非负的数量以及相应数量的记录,然后打印你的结果并带有一个最终的换行符。

C++ 参考代码使用 std::map 来实现有序键,使用 const 引用进行只读访问,并使用十进制字符串辅助函数来避免固定宽度的有符号整数溢出。请使用 Python 的 dict、int 以及显式排序;你不需要移植十进制算术辅助函数。两个版本都在过滤前进行聚合。对于记录 pen 3、book 2、pen -1,输出为 book:2,后跟 pen:2。

C++17 参考代码:inventory.cpp

#include <algorithm>
#include <iostream>
#include <map>
#include <sstream>
#include <string>
#include <vector>
// Decimal strings keep the Python contract: built-in signed overflow is avoided.
struct Integer {
    bool negative = false;
    std::string digits = "0";
};
Integer parse_integer(std::string text) {
    bool negative = text.front() == '-';
    if (text.front() == '-' || text.front() == '+') text.erase(0, 1);
    auto first = text.find_first_not_of('0');
    text = first == std::string::npos ? "0" : text.substr(first);
    return {negative && text != "0", text};
}
int compare(const std::string& a, const std::string& b) {
    if (a.size() != b.size()) return a.size() < b.size() ? -1 : 1;
    return a == b ? 0 : a < b ? -1 : 1;
}
std::string add_digits(std::string a, std::string b) {
    std::string out;
    int carry = 0;
    while (!a.empty() || !b.empty() || carry) {
        int sum = carry;
        if (!a.empty()) { sum += a.back() - '0'; a.pop_back(); }
        if (!b.empty()) { sum += b.back() - '0'; b.pop_back(); }
        out.push_back(static_cast<char>('0' + sum % 10));
        carry = sum / 10;
    }
    std::reverse(out.begin(), out.end());
    return out;
}
// Requires a >= b. Inputs are normalized nonnegative decimal magnitudes.
std::string subtract_digits(std::string a, std::string b) {
    std::string out;
    int borrow = 0;
    while (!a.empty()) {
        int digit = a.back() - '0' - borrow;
        a.pop_back();
        if (!b.empty()) { digit -= b.back() - '0'; b.pop_back(); }
        borrow = digit < 0;
        if (borrow) digit += 10;
        out.push_back(static_cast<char>('0' + digit));
    }
    while (out.size() > 1 && out.back() == '0') out.pop_back();
    std::reverse(out.begin(), out.end());
    return out;
}
Integer add(const Integer& a, const Integer& b) {
    if (a.negative == b.negative) return {a.negative, add_digits(a.digits, b.digits)};
    int order = compare(a.digits, b.digits);
    if (order == 0) return {};
    if (order > 0) return {a.negative, subtract_digits(a.digits, b.digits)};
    return {b.negative, subtract_digits(b.digits, a.digits)};
}
std::string inventory(const std::vector<std::string>& lines) {
    std::map<std::string, Integer> stock;
    for (const auto& line : lines) {
        std::istringstream fields(line);
        std::string name, amount;
        fields >> name >> amount;
        stock[name] = add(stock[name], parse_integer(amount));
    }
    std::string result;
    for (const auto& [name, amount] : stock) {
        if (!amount.negative && amount.digits != "0") {
            if (!result.empty()) result += '\n';
            result += name + ":" + amount.digits;
        }
    }
    return result.empty() ? "empty" : result;
}
int main() {
    int count;
    std::cin >> count;
    std::string line;
    std::getline(std::cin, line);
    std::vector<std::string> lines;
    for (int i = 0; i < count; ++i) {
        std::getline(std::cin, line);
        lines.push_back(line);
    }
    std::cout << inventory(lines) << '\n';
}

你的代码请写在 inventory.py 中。被锁定的 driver.py 提供输入/输出,无法编辑。

亲手试试

from inventory import inventory

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

面向 C++ 开发者的 Python 课程中的所有课

自己练习: Python 在线编译器