Menu
CoddyTech

C++ 인벤토리 이식하기

Coddy의 C++ 개발자를 위한 Python 코스 레슨. 48개 중 47번째.

challenge icon

챌린지

초급

아래의 C++17 재고 프로그램을 이식하세요. inventory.py에 inventory(lines)를 구현하세요. 이 함수는 올바른 형식의 name amount 문자열을 받아 끝에 줄바꿈이 없는 출력 텍스트를 반환합니다. 이름은 비어 있지 않은 소문자 ASCII 영문자이고 수량은 부호가 있는 10진수 정수입니다. 음수 중간 합계를 포함하여 이름별로 모든 업데이트를 더하세요. 집계 후 0 이하의 총합은 삭제하세요. 이름을 기준으로 오름차순 정렬하여 줄바꿈으로 연결된 양수 name:total 항목을 반환하거나, 남은 항목이 없으면 empty를 반환하세요. 이 함수 내에서 입력을 읽거나 출력하지 마세요. 잠긴 driver.py는 0 이상의 개수와 그 개수만큼의 레코드를 읽은 다음 마지막 줄바꿈과 함께 결과를 출력합니다.

C++ 참조 코드는 정렬된 키를 위해 std::map을 사용하고, 읽기 전용 접근을 위해 const 참조를 사용하며, 고정 너비 부호 있는 오버플로를 방지하기 위해 10진수 문자열 헬퍼를 사용합니다. Python dict, int 및 명시적 정렬을 사용하세요. 10진수 연산 헬퍼는 이식할 필요가 없습니다. 두 버전 모두 필터링 전에 집계합니다. 레코드 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 컴파일러