הסבת מערכת מלאי ב-C++
שיעור 47 מתוך 48 בקורס Python למפתחי C++ של Coddy.
אתגר
מתחיליםבצעו פורטינג לתוכנית המלאי ב-C++17 המלאה שמופיעה למטה. ממשו את inventory(lines) ב-inventory.py; היא מקבלת מחרוזות name amount תקינות ומחזירה טקסט פלט ללא שורה חדשה בסוף. שמות הם אותיות ASCII קטנות שאינן ריקות והכמויות הן מספרים שלמים מכוונים בבסיס עשר. סכמו כל עדכון לפי שם, כולל סכומי ביניים שליליים. לאחר הקיבוץ, הסירו סכומים של אפס או פחות. החזירו רשומות name:total חיוביות בסדר עולה של השם, מופרדות בשורות חדשות, או empty אם לא נותרו כאלה. אין לקרוא קלט או להדפיס בתוך פונקציה זו. הקובץ הנעול driver.py קורא כמות לא-שלילית וכמספר הזה רשומות, ואז מדפיס את התוצאה שלכם עם שורה חדשה בסוף.
קוד הרפרנס ב-C++ משתמש ב-std::map עבור מפתחות ממוינים, בהפניות מסוג const עבור גישה לקריאה בלבד, ובפונקציות עזר למחרוזות עשרוניות כדי למנוע גלישת מספרים שלמים מכוונים ברוחב קבוע. השתמשו ב-dict, ב-int ובמיון מפורש ב-Python; אינכם צריכים לבצע פורטינג לפונקציות העזר של האריתמטיקה העשרונית. שתי הגרסאות מקבצות לפני הסינון. עבור הרשומות 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))
כל השיעורים ביחידה Python למפתחי C++
1מ-C++ ל-Python
הרץ את תוכנית ה-Python הראשונה שלךמ-Streams ל-printשמות, auto, ו-constחילוק וטווח מספרים שלמיםבלוקים וטווח שמותסיכום: כתיבה מחדש של קבלה4איטרציות וטרנספורמציות
לולאות טווח והשמה מחדשאיברים ו-enumerateבקרת לולאות ללא ++אלגוריתמים ו-Comprehensionsסיכום: בניית דירוג2ערכים והחלטות
None, nullptr ו-boolערכים, כתובות, זהותבדיקות אמת ואופרנדיםהסתעפויות ובחירת ערכיםסיכום: כללי זכאות3הרגלי STL ואובייקטי Python
מ-vector ל-listTuples ו-Structured BindingsMaps, מפתחות וסדרהעתקות ערך ורשימות משותפותסיכום: ניקוי מלאי6שגיאות, משאבים ומודולים
קלט טקסט ופלט מדויקחריגות ו-RAIIמודולים במקום Headersרמזים אינם טיפוסים סטטייםסיכום: אימות אצווהתרגלו בעצמכם: קומפיילר Python אונליין