Menu
CoddyTech

Migre um inventário em Swift

Lição 47 de 48 do curso Python para desenvolvedores Swift da Coddy.

challenge icon

Desafio

Iniciante

Faça o porte completo do programa de inventário em Swift abaixo. Implemente inventory(lines) em inventory.py. Ele recebe strings bem formadas name amount e retorna o texto de saída sem uma quebra de linha final. Os nomes são compostos por letras ASCII minúsculas não vazias; as quantidades são inteiros com sinal na base dez. Some todas as atualizações de cada nome, incluindo totais intermediários negativos. Após a agregação, descarte os totais iguais ou menores que zero. Retorne as entradas positivas name:total em ordem crescente de nome, separadas por quebras de linha, ou empty se não restar nenhuma. Não leia a entrada nem imprima nessa função. O driver.py bloqueado lê uma contagem não negativa e essa quantidade de registros, então imprime o resultado com uma quebra de linha final.

A referência em Swift usa um Dictionary de valores decimais com sinal e, em seguida, ordena os nomes explicitamente. O auxiliar decimal evita o estouro de Int de largura fixa e não exige nenhum pacote de terceiros. O int do Python substitui esse auxiliar; dict mais sorted preserva o mesmo contrato. Não filtre os totais intermediários negativos antes que todas as atualizações sejam acumuladas. Para pen 3, book 2, pen -1, retorne book:2 seguido de 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"))

Seu código deve ficar em inventory.py. O driver.py bloqueado fornece a entrada e a saída e não pode ser editado.

Experimente você mesmo

from inventory import inventory

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

Todas as lições de Python para desenvolvedores Swift

Pratique por conta própria: Compilador de Python online