Adatta un inventario in Swift
Lezione 47 di 48 del corso Python per sviluppatori Swift di Coddy.
Sfida
PrincipiantePorta il programma completo per l’inventario scritto in Swift qui sotto. Implementa inventory(lines) in inventory.py. Riceve stringhe name amount ben formate e restituisce il testo di output senza un carattere di nuova riga finale. I nomi sono composti da lettere ASCII minuscole non vuote; gli importi sono interi con segno in base dieci. Somma tutti gli aggiornamenti per ciascun nome, compresi i totali intermedi negativi. Dopo l’aggregazione, scarta i totali pari o inferiori a zero. Restituisci le voci positive name:total in ordine crescente per nome, separate da caratteri di nuova riga, oppure empty se non ne rimane nessuna. Non leggere l’input né stampare in questa funzione. Il file bloccato driver.py legge un conteggio non negativo e altrettanti record, poi stampa il risultato seguito da un carattere di nuova riga finale.
La soluzione di riferimento in Swift usa un Dictionary di valori decimali con segno, poi ordina esplicitamente i nomi. L’helper per i decimali evita l’overflow di Int a larghezza fissa e non richiede pacchetti di terze parti. In Python, int sostituisce quell’helper; dict di Python insieme a sorted mantiene lo stesso comportamento previsto. Non filtrare i totali intermedi negativi prima di aver accumulato tutti gli aggiornamenti. Per pen 3, book 2, pen -1, restituisci book:2 seguito da 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"))Inserisci il tuo codice in inventory.py. Il file bloccato driver.py gestisce input e output e non può essere modificato.
Provalo tu
from inventory import inventory
lines = [input() for _ in range(int(input()))]
print(inventory(lines))
Tutte le lezioni di Python per sviluppatori Swift
1Da Swift a Python
Esegui il tuo primo programma PythonStampa e stringhelet, var e riassegnazioneIntervalli Int e divisioneIndentazione e ambito dei blocchiRiepilogo: riscrivi una ricevuta4Iterazione e trasformazioni
for e intervalli semiapertida enumerati a enumeratewhile e controllo del ciclomap, filter e comprehensionRiepilogo: creare una classifica7Istanze e stato condiviso
Struct e attributi dinamiciDa init a __init__self e riferimenti ai metodiProprietà di tipo e ombreggiamentoProprietà calcolate e testoRiepilogo: modellare un conto bancario10Metti a frutto la tua esperienza con Swift
Adatta un inventario in SwiftProgetta un sistema di prenotazione2Valori e decisioni
Optional e NoneEquatable e identitàCondizioni Bool e valori di ripiegoRami e operatori ternariRiepilogo: regole di idoneità3Dai tipi valore agli oggetti condivisi
Da array a listaTuple e spacchettamentoRicerca e ordine nei dizionariCopie di valori e aliasRiepilogo: ripulire un inventario6Errori e moduli
Input e formattazione delle stringhethrows, defer e withModuli e guardie mainSuggerimenti e tipi a runtimeRiepilogo: convalida di un batch9Progetto: Elaborazione degli ordini
Crea il modello dell'ordineAggiungi le politiche di prezzoEsercitati da solo: Compilatore Python online