Menu
CoddyTech

העבירו מלאי שנכתב ב-Swift

שיעור 47 מתוך 48 בקורס Python למפתחי Swift של Coddy.

challenge icon

אתגר

מתחילים

התאימו את תוכנית המלאי המלאה ב-Swift שלהלן. ממשו את inventory(lines) בתוך inventory.py. היא מקבלת מחרוזות תקינות בפורמט name amount ומחזירה טקסט פלט ללא ירידת שורה בסוף. השמות הם אותיות ASCII קטנות ולא ריקות; הכמויות הן מספרים שלמים עם סימן בבסיס עשרוני. סכמו את כל העדכונים עבור כל שם, כולל סכומי ביניים שליליים. לאחר צבירת הנתונים, הסירו סכומים ששווים לאפס או קטנים ממנו. החזירו רשומות חיוביות בפורמט name:total בסדר שמות עולה, מופרדות בשורות חדשות, או empty אם לא נותרו רשומות. אין לקרוא קלט או להדפיס מתוך הפונקציה הזו. הקובץ הנעול driver.py קורא מספר לא שלילי ולאחר מכן את מספר הרשומות הזה, ואז מדפיס את התוצאה עם ירידת שורה בסוף.

מימוש הייחוס ב-Swift משתמש ב-Dictionary של ערכים עשרוניים עם סימן, ואז ממיין את השמות במפורש. העזר העשרוני מונע גלישה של Int ברוחב קבוע ואינו דורש חבילה של צד שלישי. ב-Python, int מחליף את העזר הזה;‏ dict של Python יחד עם sorted שומרים על אותו חוזה. אין לסנן סכומי ביניים שליליים לפני צבירת כל העדכונים. עבור pen 3,‏ book 2,‏ pen -1, יש להחזיר את book:2 ואחריו את pen:2.

// Signed decimal arithmetic avoids fixed-width Int overflow.
struct DecimalValue {
    var negative: Bool
    var digits: [Int] // Least significant digit first.
    init(_ text: String) {
        negative = text.first == "-"
        let body = text.first == "-" || text.first == "+" ? String(text.dropFirst()) : text
        digits = body.reversed().map { Int(String($0))! }
        normalize()
    }
    mutating func normalize() {
        while digits.last == 0 { digits.removeLast() }
        if digits.isEmpty { negative = false }
    }
    func magnitudeLess(than other: DecimalValue) -> Bool {
        if digits.count != other.digits.count { return digits.count < other.digits.count }
        for (a, b) in zip(digits.reversed(), other.digits.reversed()) {
            if a != b { return a < b }
        }
        return false
    }
    // The receiver must have at least the magnitude of other.
    mutating func subtractMagnitude(_ other: DecimalValue) {
        var borrow = 0
        for i in digits.indices {
            let rhs = i < other.digits.count ? other.digits[i] : 0
            var difference = digits[i] - rhs - borrow
            borrow = difference < 0 ? 1 : 0
            if difference < 0 { difference += 10 }
            digits[i] = difference
        }
    }
    mutating func add(_ other: DecimalValue) {
        if negative == other.negative {
            let count = max(digits.count, other.digits.count)
            digits += Array(repeating: 0, count: count - digits.count)
            var carry = 0
            for i in 0..<count {
                let rhs = i < other.digits.count ? other.digits[i] : 0
                let sum = digits[i] + rhs + carry
                digits[i] = sum % 10
                carry = sum / 10
            }
            if carry > 0 { digits.append(carry) }
        } else if magnitudeLess(than: other) {
            let old = self
            self = other
            subtractMagnitude(old)
        } else {
            subtractMagnitude(other)
        }
        normalize()
    }
    var positive: Bool { !negative && !digits.isEmpty }
    var positiveText: String { digits.reversed().map(String.init).joined() }
}
let count = Int(readLine()!)!
var stock: [String: DecimalValue] = [:]
for _ in 0..<count {
    let parts = readLine()!.split(whereSeparator: { $0.isWhitespace })
    let name = String(parts[0])
    var total = stock[name] ?? DecimalValue("0")
    total.add(DecimalValue(String(parts[1])))
    stock[name] = total
}
let names = stock.keys.filter { stock[$0]!.positive }.sorted()
let output = names.map { "\($0):\(stock[$0]!.positiveText)" }
print(output.isEmpty ? "empty" : output.joined(separator: "\n"))

יש לכתוב את הקוד שלך ב-inventory.py. הקובץ הנעול driver.py מספק קלט/פלט ואי אפשר לערוך אותו.

נסו בעצמכם

from inventory import inventory

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

כל השיעורים ביחידה Python למפתחי Swift

תרגלו בעצמכם: קומפיילר Python אונליין