Menu
CoddyTech

Trasferire un inventario in R

Lezione 47 di 48 del corso Python per sviluppatori R di Coddy.

challenge icon

Sfida

Principiante

Converti l'intera implementazione di riferimento in R base riportata qui sotto. Implementa inventory(lines) in inventory.py, che è modificabile. Ogni record è una stringa name amount ben formata, con un nome ASCII minuscolo non vuoto e un importo intero decimale con segno. Aggrega tutti gli aggiornamenti, mantenendo i totali intermedi negativi. Dopo tutti gli aggiornamenti, conserva solo i totali positivi, ordina i nomi in ordine crescente e restituisci righe name:total unite da caratteri di nuova riga, oppure empty se non ne rimane nessuno. Restituisci il testo senza una nuova riga finale. Il file bloccato driver.py legge un conteggio non negativo e altrettante righe, quindi stampa il testo restituito con una nuova riga finale.

Il riferimento in R memorizza i totali in un ambiente e usa l'aritmetica su stringhe decimali, così i valori grandi restano esatti senza pacchetti esterni. In Python, int sostituisce queste funzioni ausiliarie. Il dizionario richiede un valore predefinito esplicito per le chiavi mancanti e il risultato richiede un'istruzione di restituzione esplicita. Non filtrare né limitare gli aggiornamenti prima dell'aggregazione. Per pen 3, book 2, pen -1, il risultato è book:2 seguito da pen:2.

R base di riferimento

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="")

Provalo tu

from inventory import inventory

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

Tutte le lezioni di Python per sviluppatori R

Esercitati da solo: Compilatore Python online