Menu
CoddyTech

Swift 재고 관리 시스템 이식하기

Coddy의 Swift 개발자를 위한 Python 코스 레슨. 48개 중 47번째.

challenge icon

챌린지

초급

아래의 완전한 Swift 재고 프로그램을 포팅하세요. inventory.py에서 inventory(lines)를 구현하세요. 이 함수는 올바른 형식의 name amount 문자열을 받아 마지막에 개행 문자가 없는 출력 텍스트를 반환합니다. 이름은 비어 있지 않은 소문자 ASCII 문자로 이루어지며, 수량은 부호가 있는 10진 정수입니다. 음수인 중간 합계도 포함해 각 이름의 모든 업데이트를 합산하세요. 합산이 끝나면 합계가 0 이하인 항목을 제외하세요. 양수인 name:total 항목을 이름의 오름차순으로 정렬하고 개행 문자로 연결해 반환하세요. 남은 항목이 없으면 empty를 반환하세요. 이 함수에서 입력을 읽거나 출력하지 마세요. 잠긴 driver.py는 음이 아닌 개수와 해당 개수만큼의 레코드를 읽은 뒤 결과를 마지막 개행 문자와 함께 출력합니다.

Swift 참고 코드는 부호가 있는 10진수 값을 Dictionary에 저장한 다음 이름을 명시적으로 정렬합니다. 10진수 보조 코드는 고정 폭 Int의 오버플로를 방지하며 타사 패키지가 필요하지 않습니다. Python에서는 이 보조 코드를 int로 대체하며, Python의 dict와 sorted를 함께 사용하면 동일한 규약을 유지할 수 있습니다. 모든 업데이트를 누적하기 전에 음수인 중간 합계를 제외하지 마세요. pen 3, book 2, pen -1이 주어지면 book:2 다음에 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"))

코드는 inventory.py에 작성하세요. 잠긴 driver.py가 입력과 출력을 처리하며 수정할 수 없습니다.

직접 해보기

from inventory import inventory

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

Swift 개발자를 위한 Python의 모든 레슨

직접 연습해 보세요: 온라인 Python 컴파일러