Port a Kotlin Inventory
Lesson 47 of 48 in Coddy's Python for Kotlin Developers course.
Challenge
BeginnerPort the Kotlin reference below. Implement inventory(lines) in inventory.py, returning text without a trailing newline. Each well-formed record has a nonempty lowercase ASCII name and a signed base-ten integer amount separated by whitespace. Sum every update, including negative intermediate totals. After aggregation, discard totals of zero or less. Sort positive entries by name and join name:total lines with newlines, or return empty when no positive totals remain. The locked driver.py reads a nonnegative count and that many records and prints the returned string with a final newline.
The Kotlin/JVM reference uses BigInteger to avoid Int and Long overflow, a mutable map with Elvis fallback, and a filter/sort/join pipeline. Python int handles these integer totals directly. Use explicit dictionary sorting; insertion order alone is not alphabetical order. A negative update may be followed by recovery, so filter only after all updates.
Kotlin reference
import java.math.BigInteger
fun inventory(lines: List<String>): String {
val stock = mutableMapOf<String, BigInteger>()
for (line in lines) {
val (name, amount) = line.trim().split(Regex("\\s+"))
stock[name] = (stock[name] ?: BigInteger.ZERO) + amount.toBigInteger()
}
val report = stock.entries.filter { it.value > BigInteger.ZERO }
.sortedBy { it.key }
.joinToString("\n") { "${it.key}:${it.value}" }
return report.ifEmpty { "empty" }
}
fun main() {
val count = readln().toInt()
val lines = List(count) { readln() }
println(inventory(lines))
}Your code goes in inventory.py. The locked driver.py supplies input/output and cannot be edited.
Try it yourself
from inventory import inventory
lines = [input() for _ in range(int(input()))]
print(inventory(lines))
All lessons in Python for Kotlin Developers
1From Kotlin to Python
Run Your First Python ProgramPrint and String TemplatesVal, Var, and Python NamesDivision and Integer WidthSuites and Block ScopeRecap: Rewrite a Receipt4Iteration and Transformations
Ranges and Loop BindingsEntries and withIndexUpdates and Loop ControlCollection PipelinesRecap: Build a Ranking2Values and Decisions
Nullable Types and NoneEquality and IdentityBoolean Conditions and orIf Expressions and ElifRecap: Eligibility Rules3Collections and Shared State
Read-only Lists and MutationPair and Tuple UnpackingMap Lookup and Missing KeysShallow Copies and SetsRecap: Clean an Inventory6Input, Errors, and Modules
Console Input and FormattingExceptions and Resource ScopeImports and Entry PointsStatic Types and AnnotationsRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler