移植 R 库存管理程序
Coddy 面向 R 开发者的 Python 课程的第 47 课,共 48 课。
挑战
入门移植下面完整的 base-R 参考实现。在可编辑的 inventory.py 中实现 inventory(lines)。每条记录都是格式正确的 name amount 字符串,其中名称为非空的小写 ASCII 字符串,数量为带符号的十进制整数。汇总所有更新,并保留中间的负总数。完成所有更新后,只保留正总数,按名称升序排序,并返回以换行符连接的 name:total 行;如果没有符合条件的记录,则返回 empty。返回的文本末尾不要带换行符。锁定的 driver.py 会读取一个非负数量和相应行数的数据,然后打印返回的文本,并在末尾添加换行符。
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 在线编译器