Menu
CoddyTech

Final: Port C# Inventory

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

challenge icon

Challenge

Beginner

Implement inventory(lines) in inventory.py. It receives a list of record strings and returns the entire report string with internal newline separators and no trailing newline. Do not read input or print in this function: the locked driver reads a nonnegative count and that many records, calls your function, and prints its return value with one final newline. Every record is a well-formed lowercase-ASCII name and signed integer amount. Accumulate all updates per name, including negative intermediate totals. Only after aggregation discard totals <= 0. Sort surviving names ascending and return name:total lines, or exactly empty. Duplicate names add rather than overwrite. The C# reference below demonstrates the same function behavior on sample data; its output is book:2 then pen:2.

Complete C# reference program

BigInteger avoids fixed-width overflow differences with Python int. Ordinal sorting matches Python ordering for the specified lowercase ASCII names. The reference uses a sample collection; only the supplied Python driver reads challenge input.

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Numerics;

public static class Program
{
    public static string Inventory(IEnumerable<string> lines)
    {
        var stock = new Dictionary<string, BigInteger>(StringComparer.Ordinal);
        foreach (string line in lines)
        {
            string[] fields = line.Split(' ', StringSplitOptions.RemoveEmptyEntries);
            string name = fields[0];
            BigInteger amount = BigInteger.Parse(fields[1], CultureInfo.InvariantCulture);
            stock.TryGetValue(name, out BigInteger previous);
            stock[name] = previous + amount;
        }
        var names = stock.Keys.Where(name => stock[name] > 0)
            .OrderBy(name => name, StringComparer.Ordinal);
        var rows = names.Select(name => name + ":" + stock[name].ToString(CultureInfo.InvariantCulture)).ToArray();
        return rows.Length == 0 ? "empty" : string.Join("\n", rows);
    }

    public static void Main()
    {
        Console.WriteLine(Inventory(new[] { "pen 3", "book 2", "pen -1" }));
    }
}

Editable implementation files: inventory.py. The locked driver.py is the supplied launcher or input/output harness and must remain unchanged.

Keep the supplied imports and exact API names. Return results or raise the required exceptions; do not read input or print from these implementation modules.

Try it yourself

from inventory import inventory

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

All lessons in Python for C# Developers

Practice on your own: Online Python compiler