Migre um inventário em Swift
Lição 47 de 48 do curso Python para desenvolvedores Swift da Coddy.
Desafio
InicianteFaç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
1De Swift para Python
Execute seu primeiro programa em PythonExibição e stringslet, var e reassociaçãoIntervalo de Int e divisãoIndentação e escopo de blocoRevisão: reescreva um recibo4Iteração e transformações
for e intervalos semiabertosde enumerated a enumeratewhile e controle de loopsmap, filter e comprehensionsRevisão: crie um ranking2Valores e decisões
Optionals e NoneEquatable e identidadeCondições Bool e alternativasRamificações e ternáriosRevisão: regras de elegibilidade3De Tipos por Valor a Objetos Compartilhados
De array para listaTuplas e desempacotamentoBusca e ordem em dicionáriosCópias de valores e aliasesRecapitulação: Organize um inventário6Erros e Módulos
Entrada e formatação de stringsthrows, defer e withMódulos e proteção de execução principalDicas de tipo e tipos em tempo de execuçãoRecapitulação: validar um lote9Projeto: Processamento de Pedidos
Criar o Modelo de PedidoAdicionar Políticas de PreçosPratique por conta própria: Compilador de Python online