Rust 재고 관리 시스템 포팅하기
Coddy의 Rust 개발자를 위한 Python 코스 레슨. 48개 중 47번째.
챌린지
초급아래의 완전한 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 컴파일러