Port a Rust Inventory
Lesson 47 of 48 in Coddy's Python for Rust Developers course.
Challenge
BeginnerPort the complete Rust inventory program below. Implement inventory(lines) in inventory.py. It receives well-formed name amount strings and returns output text without a trailing newline. Names are nonempty lowercase ASCII letters; amounts are signed base-ten integers. Sum all updates for each name, including negative intermediate totals. After aggregation, discard totals of zero or less. Return positive name:total entries in ascending name order, joined by newlines, or empty if none remain. Do not read input or print in this function. The locked driver.py reads a nonnegative count and that many records, then prints the result with a final newline.
The Rust reference owns names in a BTreeMap and mutates entries through entry. Its small signed-decimal type avoids fixed-width overflow without external crates. Python int replaces that helper, and sorted supplies the ordering that BTreeMap guarantees. Both programs aggregate before filtering. For pen 3, book 2, pen -1, return book:2 followed by 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") });
}Your code goes in inventory.py. The locked driver.py supplies input/output and cannot be edited.
Try it yourself
from inventory import inventory
lines = [input() for _ in range(int(input()))]
print(inventory(lines))
All lessons in Python for Rust Developers
1From Rust to Python
Run Your First Python ProgramMacros to printBindings, mut, and ShadowingIntegers and Floor DivisionIndentation and ScopeRecap: Rewrite a Receipt4Iteration and Transformations
Borrowed Iteration to forEntries and enumeratewhile, break, and continueIterators and ComprehensionsRecap: Build a Ranking2Values and Decisions
Option and NoneEquality and Object IdentityTruth Tests and FallbacksIf Expressions and elifRecap: Eligibility Rules3Ownership and Collections
Vec to listTuples and DestructuringHashMap to dictClone and Shallow CopiesRecap: Clean an Inventory6Errors and Modules
Text Input and FormattingResult, Exceptions, and withModules and the Main GuardHints Without Borrow CheckingRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler