Port an R Inventory
Lesson 47 of 48 in Coddy's Python for R Developers course.
Challenge
BeginnerPort the complete base-R reference below. Implement inventory(lines) in editable inventory.py. Each record is a well-formed name amount string with a nonempty lowercase ASCII name and signed decimal integer amount. Aggregate all updates, retaining negative intermediate totals. After all updates, keep only positive totals, sort names ascending, and return name:total lines joined with newlines, or empty if none remain. Return text without a trailing newline. The locked driver.py reads a nonnegative count and that many lines, then prints the returned text with a final newline.
The R reference stores totals in an environment and uses decimal-string arithmetic so large values remain exact without external packages. Python int replaces those helpers. Its dictionary needs an explicit missing-key fallback, and its result needs an explicit return. Do not filter or clamp updates before aggregation. For pen 3, book 2, pen -1, output is book:2 then pen:2.
Base R reference
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="")Try it yourself
from inventory import inventory
lines = [input() for _ in range(int(input()))]
print(inventory(lines))
All lessons in Python for R Developers
1From R to Python
Run Your First Python Programcat, print, and StringsBindings and Copy SemanticsInteger Arithmetic and NABraces Become SuitesRecap: Rewrite a Receipt4Iteration and Transformations
seq_along and rangeitems and enumeratenext and continuelapply and ComprehensionsRecap: Build a Ranking2Values and Decisions
NULL, NA, and NoneVector Equality and IdentityScalar Conditions, Not Vectorsifelse and Scalar SelectionRecap: Eligibility Rules3Vectors to Containers
Vectors, Lists, and Index ZeroTuples and Exact UnpackingNamed Lists and Dictionariesunique and Shallow CopiesRecap: Clean an Inventory6Reliable Python Programs
readLines and Text ContractsConditions and Cleanupsource and Module ImportsAnnotations and Runtime TypesRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler