Rustの在庫管理を移植する
Coddyの「Rust開発者のためのPython」コースのレッスン 47/48。
チャレンジ
初心者以下のRustの在庫管理プログラム全体を移植してください。inventory.pyにinventory(lines)を実装します。この関数は形式が正しいname amount文字列を受け取り、末尾に改行のない出力テキストを返します。名前は空でない小文字のASCII文字で、数量は符号付きの10進整数です。各名前について、途中で合計が負になっても、すべての更新を合計します。集計後、合計が0以下の項目を除外します。正のname:totalの項目を名前の昇順に並べて改行で結合して返すか、残る項目がなければemptyを返します。この関数内で入力を読み込んだり、出力を表示したりしないでください。編集できないdriver.pyは、0以上の件数とその数のレコードを読み込み、結果を最後に改行を付けて出力します。
Rustの参照実装はBTreeMapに名前を保持し、entryを使って項目を更新します。この小さな符号付き10進数型は、外部クレートを使わずに固定幅整数のオーバーフローを避けます。Pythonではintでこの補助型を置き換え、sortedでBTreeMapが保証する順序を実現します。どちらのプログラムも、フィルタリングの前に集計します。pen 3、book 2、pen -1に対して、book:2に続いてpen:2を返します。
use std::cmp::Ordering;
use std::collections::BTreeMap;
use std::io::{self, Read};
// Signed decimal arithmetic keeps the reference independent of integer width.
#[derive(Clone, Default)]
struct Decimal { negative: bool, digits: Vec<u8> }
impl Decimal {
fn parse(text: &str) -> Self {
let negative = text.starts_with('-');
let raw = text.trim_start_matches(|c| c == '+' || c == '-');
let mut value = Self { negative, digits: raw.bytes().rev().map(|b| b - b'0').collect() };
value.normalize();
value
}
fn normalize(&mut self) {
while self.digits.last() == Some(&0) { self.digits.pop(); }
if self.digits.is_empty() { self.negative = false; }
}
fn magnitude_cmp(&self, other: &Self) -> Ordering {
self.digits.len().cmp(&other.digits.len())
.then_with(|| self.digits.iter().rev().cmp(other.digits.iter().rev()))
}
fn add(&mut self, other: &Self) {
if self.negative == other.negative {
let length = self.digits.len().max(other.digits.len());
self.digits.resize(length, 0);
let mut carry = 0;
for i in 0..length {
let sum = self.digits[i] + other.digits.get(i).copied().unwrap_or(0) + carry;
self.digits[i] = sum % 10;
carry = sum / 10;
}
if carry != 0 { self.digits.push(carry); }
} else {
if self.magnitude_cmp(other) == Ordering::Less {
let old = self.clone();
*self = other.clone();
self.subtract_magnitude(&old);
} else { self.subtract_magnitude(other); }
}
self.normalize();
}
// Precondition: self has at least the magnitude of other.
fn subtract_magnitude(&mut self, other: &Self) {
let mut borrow: i16 = 0;
for i in 0..self.digits.len() {
let mut difference = self.digits[i] as i16
- other.digits.get(i).copied().unwrap_or(0) as i16 - borrow;
borrow = if difference < 0 { 1 } else { 0 };
if difference < 0 { difference += 10; }
self.digits[i] = difference as u8;
}
}
fn positive(&self) -> bool { !self.negative && !self.digits.is_empty() }
fn positive_text(&self) -> String {
self.digits.iter().rev().map(|d| (b'0' + d) as char).collect()
}
}
fn main() {
let mut input = String::new();
io::stdin().read_to_string(&mut input).expect("read input");
let mut lines = input.lines();
let count: usize = lines.next().expect("count").parse().expect("nonnegative count");
let mut stock: BTreeMap<String, Decimal> = BTreeMap::new();
for line in lines.take(count) {
let mut fields = line.split_whitespace();
let name = fields.next().expect("name").to_owned();
let amount = Decimal::parse(fields.next().expect("amount"));
stock.entry(name).or_default().add(&amount);
}
let output: Vec<String> = stock.iter().filter(|(_, v)| v.positive())
.map(|(k, v)| format!("{}:{}", k, v.positive_text())).collect();
println!("{}", if output.is_empty() { String::from("empty") } else { output.join("\n") });
}コードはinventory.pyに記述してください。編集できないdriver.pyが入出力を処理するため、変更できません。
自分で試してみよう
from inventory import inventory
lines = [input() for _ in range(int(input()))]
print(inventory(lines))
Rust開発者のためのPythonのすべてのレッスン
自分で練習してみよう: Pythonオンラインコンパイラ