Menu
CoddyTech

Port a Kotlin Inventory

Lesson 47 of 48 in Coddy's Python for Kotlin Developers course.

challenge icon

Challenge

Beginner

Port 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

Practice on your own: Online Python compiler