Menu
CoddyTech

R 재고 시스템 포팅하기

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

challenge icon

챌린지

초급

아래의 완전한 Base R 참조 구현을 옮기세요. 편집 가능한 inventory.py에 inventory(lines)를 구현하세요. 각 레코드는 비어 있지 않은 소문자 ASCII 이름과 부호가 있는 십진 정수 수량으로 이루어진 올바른 형식의 name amount 문자열입니다. 음수인 중간 합계를 유지하면서 모든 업데이트를 합산하세요. 업데이트를 모두 적용한 뒤 양수인 합계만 남기고, 이름을 오름차순으로 정렬한 다음, 각 줄이 name:total인 문자열을 줄바꿈으로 연결해 반환하세요. 남은 항목이 없다면 empty를 반환하세요. 반환 텍스트 끝에는 줄바꿈을 넣지 마세요. 잠긴 driver.py는 0 이상의 개수와 해당 개수만큼의 줄을 읽은 뒤, 반환된 텍스트를 출력하고 마지막에 줄바꿈을 출력합니다.

R 참조 구현은 환경에 합계를 저장하고, 외부 패키지 없이도 큰 수를 정확하게 유지하도록 십진 문자열 연산을 사용합니다. Python에서는 이러한 도우미를 int로 대체합니다. 딕셔너리에는 키가 없을 때 사용할 값을 명시적으로 지정해야 하며, 결과도 명시적으로 반환해야 합니다. 합산 전에 업데이트를 필터링하거나 제한하지 마세요. pen 3, book 2, pen -1의 경우 출력은 먼저 book:2, 그다음 pen:2입니다.

Base R 참조 구현

normalize <- function(text) {
  negative <- startsWith(text, "-")
  digits <- sub("^[+-]", "", text)
  digits <- sub("^0+", "", digits)
  if (!nzchar(digits)) return("0")
  if (negative) paste0("-", digits) else digits
}
decimal_add <- function(left, right) {
  left <- normalize(left); right <- normalize(right)
  left_negative <- startsWith(left, "-")
  right_negative <- startsWith(right, "-")
  a <- sub("^-", "", left); b <- sub("^-", "", right)
  da <- as.integer(strsplit(a, "", fixed=TRUE)[[1]])
  db <- as.integer(strsplit(b, "", fixed=TRUE)[[1]])
  compare <- sign(length(da) - length(db))
  if (compare == 0) {
    different <- which(da != db)
    if (length(different)) compare <- sign(da[different[1]] - db[different[1]])
  }
  same_sign <- left_negative == right_negative
  if (!same_sign && compare == 0) return("0")
  if (!same_sign && compare < 0) {
    swap <- da; da <- db; db <- swap
  }
  negative <- if (same_sign || compare > 0) left_negative else right_negative
  da <- rev(da); db <- rev(db)
  width <- max(length(da), length(db))
  length(da) <- width; length(db) <- width
  da[is.na(da)] <- 0L; db[is.na(db)] <- 0L
  result <- integer(width); carry <- 0L
  for (i in seq_len(width)) {
    if (same_sign) {
      digit <- da[i] + db[i] + carry
      result[i] <- digit %% 10L; carry <- digit %/% 10L
    } else {
      digit <- da[i] - db[i] - carry
      carry <- as.integer(digit < 0L)
      result[i] <- digit + 10L * carry
    }
  }
  if (same_sign && carry > 0L) result <- c(result, carry)
  text <- paste0(rev(result), collapse="")
  normalize(paste0(if (negative) "-" else "", text))
}
inventory <- function(lines) {
  stock <- new.env(parent=emptyenv())
  for (line in lines) {
    parts <- strsplit(trimws(line), "[[:space:]]+")[[1]]
    name <- parts[[1]]
    previous <- if (exists(name, stock, inherits=FALSE)) stock[[name]] else "0"
    stock[[name]] <- decimal_add(previous, parts[[2]])
  }
  keys <- sort(ls(stock), method="radix")
  keys <- keys[vapply(keys, function(key) {
    value <- stock[[key]]
    value != "0" && !startsWith(value, "-")
  }, logical(1))]
  if (!length(keys)) return("empty")
  paste(vapply(keys, function(key) paste0(key, ":", stock[[key]]), character(1)), collapse="\n")
}
input <- readLines(file("stdin"), warn=FALSE)
count <- as.integer(input[[1]])
lines <- if (count == 0L) character(0) else input[seq_len(count) + 1L]
cat(inventory(lines), "\n", sep="")

직접 해보기

from inventory import inventory

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

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

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