最終課題:センサーポリシー
Coddyの「Python開発者のためのRust」コースのレッスン 48/48。
チャレンジ
中級Pythonの参照実装を移植し、ダックタイピングによる受け入れポリシーを明示的なRustのトレイトに置き換えてください。Pythonの例外はResult値に置き換え、Pythonの整数には参照パーサーと同じ明示的なi32の範囲制限を適用してください。入力は、i32の整数しきい値に続いて、空白で区切られた読み取りトークンが最大100個並びます。各トークンはASCIIバイトで最大31バイトです。有効な読み取り値は、先頭に符号を任意で付けた10進数字で、i32の範囲内に収まります。累計値もすべてi32の範囲内に収まります。reading::parse(text: &str) -> Result<i32, &'static str>は、前後に空白のないトークン全体を受け付け、それ以外の場合はErr("invalid")を返します。Accept::accept(&self, value: i32) -> boolがポリシーの契約です。Above::new(limit: i32) -> Aboveは、しきい値より大きい値のみを受け付けます。Report::new() -> Reportは空の状態で開始します。feed<R: Accept + ?Sized>(&mut self, value: i32, rule: &R)は、受け付けた読み取り値を件数と合計に加算し、拒否された読み取り値では状態を維持します。count(&self) -> usizeとtotal(&self) -> i32は状態を参照するメソッドです。トレイトオブジェクトを含め、呼び出し側で定義したAcceptポリシーも動作しなければなりません。入力処理にはAboveを使用し、count total invalidを出力してください。読み取り値がない場合は0 0 0を出力します。
必要な公開APIを実装し、exercise::solve(input: &str) -> Stringから結果を返してください。末尾に改行を付けてはいけません。編集可能なコード内では出力しないでください。編集できないドライバーは必要なAPIを個別に確認し、標準入力をすべて読み取って、返されたテキストを末尾に改行を1つ付けて出力します。
コードはexercise.rs、rule.rs、above.rs、report.rs、reading.rsに記述してください。main.rsには用意された入出力コードがあり、編集できません。
同じ有効な入力仕様に対するPythonの完全な参照実装:
"""Python reference with explicit ASCII/i32 parsing and a duck-typed policy."""
import re
import sys
def parse(text):
if re.fullmatch(r"[+-]?[0-9]+", text) is None:
raise ValueError("invalid")
value = int(text)
if not -(2 ** 31) <= value <= 2 ** 31 - 1:
raise ValueError("invalid")
return value
class Above:
def __init__(self, limit):
self.limit = limit
def accept(self, value):
return value > self.limit
class Report:
def __init__(self):
self.count = 0
self.total = 0
def feed(self, value, rule):
if rule.accept(value):
self.count += 1
self.total += value
def solve(text):
tokens = text.split()
rule = Above(int(tokens[0]))
report = Report()
invalid = 0
for token in tokens[1:]:
try:
value = parse(token)
except ValueError:
invalid += 1
continue
report.feed(value, rule)
return f"{report.count} {report.total} {invalid}"
if __name__ == "__main__":
print(solve(sys.stdin.read()))自分で試してみよう
#![allow(dead_code, unused_imports, unused_variables, unused_mut)]
mod exercise;
mod rule;
mod above;
mod report;
mod reading;
use std::io::{self, Read};
fn main() {
let mut input=String::new();
io::stdin().read_to_string(&mut input).unwrap();
// 公開 API のテスト開始
use rule::Accept;
let p=above::Above::new(-3); assert!(p.accept(-2)); assert!(!p.accept(-3)); assert!(!p.accept(-4));
assert_eq!(reading::parse("+17"), Ok(17)); assert_eq!(reading::parse("-0"), Ok(0));
for s in &["", "+", " 3", "2x", "2147483648"] { assert_eq!(reading::parse(s), Err("invalid")); }
struct Odd;
impl rule::Accept for Odd { fn accept(&self, value: i32) -> bool { value % 2 != 0 } }
let policy: &dyn rule::Accept=&Odd;
let mut r=report::Report::new(); assert_eq!(r.count(),0); assert_eq!(r.total(),0);
r.feed(-7,policy); r.feed(4,policy); r.feed(9,policy);
assert_eq!(r.count(),2); assert_eq!(r.total(),2);
r.feed(0,policy); assert_eq!(r.count(),2); assert_eq!(r.total(),2);
r.feed(1,&p); assert_eq!(r.count(),3); assert_eq!(r.total(),3);
assert_eq!(report::Report::new().count(),0);
// 公開 API のテスト終了
println!("{}", exercise::solve(&input));
}
Python開発者のためのRustのすべてのレッスン
自分で練習してみよう: Rustオンラインコンパイラ