Menu
CoddyTech

Port a Swift Inventory

Lesson 47 of 48 in Coddy's Python for Swift Developers course.

challenge icon

Challenge

Beginner

Port the complete Swift inventory program below. Implement inventory(lines) in inventory.py. It receives well-formed name amount strings and returns output text without a trailing newline. Names are nonempty lowercase ASCII letters; amounts are signed base-ten integers. Sum all updates for each name, including negative intermediate totals. After aggregation, discard totals of zero or less. Return positive name:total entries in ascending name order, joined by newlines, or empty if none remain. Do not read input or print in this function. The locked driver.py reads a nonnegative count and that many records, then prints the result with a final newline.

The Swift reference uses a Dictionary of signed-decimal values, then sorts names explicitly. The decimal helper avoids fixed-width Int overflow and requires no third-party package. Python int replaces that helper; Python dict plus sorted preserves the same contract. Do not filter negative intermediate totals before all updates are accumulated. For pen 3, book 2, pen -1, return book:2 followed by 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"))

Your code goes in inventory.py. The locked driver.py supplies input/output and cannot be edited.

Try it yourself

from inventory import inventory

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

All lessons in Python for Swift Developers

Practice on your own: Online Python compiler