Menu
CoddyTech

Przenieś magazyn napisany w Swift

Lekcja 47 z 48 w kursie Python dla programistów Swift w Coddy.

challenge icon

Wyzwanie

Początkujący

Przenieś cały poniższy program inwentaryzacyjny w Swift. Zaimplementuj inventory(lines) w pliku inventory.py. Otrzymuje on poprawnie sformatowane ciągi name amount i zwraca tekst wyjściowy bez końcowego znaku nowej linii. Nazwy to niepuste ciągi składające się z małych liter ASCII; wartości to liczby całkowite ze znakiem w systemie dziesiętnym. Zsumuj wszystkie aktualizacje dla każdej nazwy, także ujemne wartości pośrednie. Po zsumowaniu odrzuć wartości równe zero lub mniejsze. Zwróć wpisy name:total z dodatnimi wartościami, uporządkowane rosnąco według nazw i połączone znakami nowej linii, albo empty, jeśli żadne nie pozostały. Nie odczytuj danych wejściowych ani niczego nie wyświetlaj w tej funkcji. Zablokowany plik driver.py odczytuje nieujemną liczbę rekordów, a następnie tyle rekordów, po czym wyświetla wynik z końcowym znakiem nowej linii.

Implementacja referencyjna w Swift używa słownika wartości dziesiętnych ze znakiem, a następnie jawnie sortuje nazwy. Pomocnicza obsługa liczb dziesiętnych pozwala uniknąć przepełnienia typu Int o stałym rozmiarze i nie wymaga zewnętrznego pakietu. W Pythonie tę funkcję zastępuje int; dict wraz z sorted zachowują ten sam kontrakt. Nie odrzucaj ujemnych wartości pośrednich, dopóki nie zostaną zsumowane wszystkie aktualizacje. Dla danych pen 3, book 2, pen -1 zwróć book:2, a następnie 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"))

Umieść swój kod w pliku inventory.py. Zablokowany plik driver.py obsługuje wejście i wyjście i nie można go edytować.

Spróbuj swoich sił

from inventory import inventory

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

Wszystkie lekcje w sekcji Python dla programistów Swift

Poćwicz samodzielnie: Kompilator Python online