最終課題:在庫を移植する
Coddyの「Python開発者のためのC#」コースのレッスン 47/48。
チャレンジ
簡単参照元の処理をC#に移植してください。2行には、カンマ区切りのASCII名と、それと同じ数の整数調整値が含まれます。1行目が空の場合、両方の列は空です。名前の前後の空白を削除して小文字に変換し、空白だけの名前は無視し、調整値を合計して、合計が0以下のものを除外し、その後、名前の序数順で並べ替えます。名前と合計値をコロンで区切った項目をカンマで連結して返します。ドライバーは先頭にitems:を付けます。
ロック解除されているC#ファイルを編集してください。表示されているロック済みのMain.csは、説明された行を読み込み、Exercise.Solveを呼び出し、入力が変更されていないことを検証して、末尾に改行を1つ付けて結果を出力します。宣言済みのAPIを維持してください。2つ目のMainを追加したり、診断出力を表示したりしないでください。
Pythonの参照プログラム
def inventory(names, changes):
totals = {}
for name, quantity in zip(names, changes):
key = name.strip().lower()
if key:
totals[key] = totals.get(key, 0) + quantity
return ",".join(f"{name}:{count}" for name, count in sorted(totals.items()) if count > 0)
print("items:" + inventory([" Tea ", "tea", "cake"], [2, 3, -1]))
自分で試してみよう
using System;
using System.Linq;
using System.Collections.Generic;
using System.Globalization;
public class Program {
static int I(string text) { return int.Parse(text,CultureInfo.InvariantCulture); }
static int[] Ints(string text) { return text.Length==0 ? new int[0] : text.Split(',').Select(I).ToArray(); }
static string[] Words(string text) { return text.Length==0 ? new string[0] : text.Split(','); }
static string Snapshot(object value) { if (value==null) return "<null>"; if (value is string) return (string)value; var sequence=value as System.Collections.IEnumerable; if (sequence!=null) { var items=new List<string>(); foreach (object item in sequence) items.Add(Snapshot(item)); return string.Join("|",items); } return Convert.ToString(value,CultureInfo.InvariantCulture); }
public static void Main() {
System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
var rows = new List<string>(); string line; while ((line=Console.ReadLine()) != null) rows.Add(line);
string[] input=rows.ToArray();
var a0 = Words(input[0]); string before0=Snapshot(a0);
var a1 = Ints(input[1]); string before1=Snapshot(a1);
var result = Exercise.Solve(a0,a1);
if (Snapshot(a0) != before0) throw new Exception("Input mutation");
if (Snapshot(a1) != before1) throw new Exception("Input mutation");
Console.WriteLine("items:" + result);
}
}
Python開発者のためのC#のすべてのレッスン
1ここから始めよう
初めてのC#プログラムを実行する自分で練習してみよう: C#オンラインコンパイラ