Migra un inventario en Swift
Lección 47 de 48 del curso Python para desarrolladores de Swift de Coddy.
Desafío
PrincipianteAdapta el programa completo de inventario de Swift que aparece a continuación. Implementa inventory(lines) en inventory.py. Recibe cadenas con formato correcto name amount y devuelve texto de salida sin un salto de línea final. Los nombres son letras ASCII minúsculas no vacías; las cantidades son enteros decimales con signo. Suma todas las actualizaciones de cada nombre, incluidos los totales intermedios negativos. Después de agregarlos, descarta los totales menores o iguales que cero. Devuelve las entradas positivas name:total en orden ascendente por nombre, unidas con saltos de línea, o empty si no queda ninguna. No leas la entrada ni imprimas nada en esta función. El driver.py bloqueado lee una cantidad no negativa y esa cantidad de registros, y luego imprime el resultado con un salto de línea final.
La referencia de Swift utiliza un Dictionary de valores decimales con signo y luego ordena los nombres explícitamente. El auxiliar decimal evita el desbordamiento de Int de ancho fijo y no requiere ningún paquete de terceros. Python int reemplaza ese auxiliar; Python dict más sorted conserva el mismo contrato. No filtres los totales intermedios negativos antes de acumular todas las actualizaciones. Para pen 3, book 2, pen -1, devuelve 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"))Tu código va en inventory.py. El driver.py bloqueado proporciona la entrada y salida y no se puede editar.
Pruébalo tú mismo
from inventory import inventory
lines = [input() for _ in range(int(input()))]
print(inventory(lines))
Todas las lecciones de Python para desarrolladores de Swift
1De Swift a Python
Ejecuta tu primer programa en PythonImprimir y cadenaslet, var y reasignaciónRango de Int y divisiónSangría y ámbito de bloqueRepaso: reescribe un recibo4Iteración y transformaciones
for y rangos semiabiertosDe enumerado a enumeratewhile y control de buclesmap, filter y comprensionesRepaso: crear una clasificación2Valores y decisiones
Opcionales y NoneEquatable e identidadCondiciones Bool y valores alternativosRamas y operadores ternariosRepaso: reglas de elegibilidad3De tipos de valor a objetos compartidos
De array a listaTuplas y desempaquetadoBúsqueda y orden en diccionariosCopias de valores y aliasRepaso: limpiar un inventario6Errores y módulos
Entrada y formato de cadenasthrows, defer y withMódulos y protecciones de ejecución principalAnotaciones y tipos en tiempo de ejecuciónRepaso: validar un lote9Proyecto: Procesamiento de pedidos
Crear el modelo de pedidoAñadir políticas de preciosPractica por tu cuenta: Compilador de Python online