Menu
CoddyTech

最终:移植 C# 库存系统

Coddy 面向 C# 开发者的 Python 课程 课程的第 47 课,共 48 课。

challenge icon

挑战

入门

在 inventory.py 中实现 inventory(lines)。它接收一个记录字符串列表,并返回由内部换行分隔符分隔且末尾没有换行符的完整报告字符串。请勿在此函数中读取输入或打印内容:被锁定的驱动程序会读取一个非负计数及相应数量的记录,调用你的函数,并打印其返回值(末尾带有最后一个换行符)。每条记录都是由格式规范的小写 ASCII 名称和有符号整数数量组成。累加每个名称的所有更新,包括负的中间总数。仅在聚合之后弃用总数 <= 0 的项。将保留下来的名称按升序排序,并返回 name:total 格式的行,或者完全为 "empty"。重复的名称相加而不是覆盖。下面的 C# 参考程序演示了在示例数据上的相同函数行为;其输出为 "book:2" 然后是 "pen:2"。

完整的 C# 参考程序

`BigInteger` 避免了与 Python `int` 之间因固定宽度导致的溢出差异。Ordinal(按序)排序符合给定的小写 ASCII 名称在 Python 中的排序顺序。该参考程序使用的是示例集合;只有提供的 Python 驱动程序才会读取挑战输入。

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" }));
    }
}

可编辑的实现文件:inventory.py。被锁定的 driver.py 是提供的启动器或输入/输出套件,必须保持不变。

保留提供的导入和确切的 API 名称。返回结果或引发所需的异常;不要在这些实现模块中读取输入或进行打印。

亲手试试

from inventory import inventory

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

面向 C# 开发者的 Python 课程中的所有课

自己练习: Python 在线编译器