Menu
CoddyTech

迁移一个 Swift 库存系统

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

challenge icon

挑战

入门

将下面完整的 Swift 库存程序移植过来。在 inventory.py 中实现 inventory(lines)。它接收格式正确的 name amount 字符串,并返回不带末尾换行符的输出文本。名称是非空的小写 ASCII 字母;数量是带符号的十进制整数。将每个名称的所有更新累加起来,包括中间的负数总值。累加完成后,丢弃小于或等于零的总值。按名称升序排列正数 name:total 条目,并用换行符连接;如果没有剩余条目,则返回 empty。不要在此函数中读取输入或打印内容。锁定的 driver.py 会读取一个非负数量和相应数量的记录,然后打印结果并在末尾添加换行符。

Swift 参考实现使用存储带符号十进制数值的 Dictionary,然后显式排序名称。十进制辅助工具可以避免定长 Int 溢出,且无需第三方包。Python 的 int 可以替代该辅助工具;Python 的 dict 和 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))

面向 Swift 开发者的 Python中的所有课

自己练习: Python 在线编译器