Adapte um inventário em Rust
Lição 47 de 48 do curso Python para desenvolvedores Rust da Coddy.
Desafio
InicianteTransponha o programa completo de inventário em Rust abaixo. Implemente inventory(lines) em inventory.py. Ele recebe strings bem-formadas name amount e retorna o texto de saída sem uma quebra de linha final. Os nomes são letras ASCII minúsculas não vazias; as quantidades são inteiros com sinal na base dez. Some todas as atualizações de cada nome, incluindo totais intermediários negativos. Após a agregação, descarte os totais menores ou iguais a zero. Retorne as entradas positivas name:total em ordem crescente de nome, separadas por quebras de linha, ou empty se nenhuma permanecer. Não leia a entrada nem imprima nada nesta função. O arquivo bloqueado driver.py lê uma contagem não negativa e esse número de registros, depois imprime o resultado com uma quebra de linha final.
A referência em Rust armazena os nomes em um BTreeMap e modifica as entradas usando entry. Seu tipo pequeno de decimais com sinal evita estouro de largura fixa sem crates externos. O int do Python substitui esse auxiliar, e sorted fornece a ordenação garantida por BTreeMap. Ambos os programas agregam antes de filtrar. Para pen 3, book 2, pen -1, retorne book:2 seguido por 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") });
}Seu código deve ficar em inventory.py. O arquivo bloqueado driver.py fornece a entrada e a saída e não pode ser editado.
Experimente você mesmo
from inventory import inventory
lines = [input() for _ in range(int(input()))]
print(inventory(lines))
Todas as lições de Python para desenvolvedores Rust
1De Rust para Python
Execute seu primeiro programa em PythonMacros para imprimirVinculações, mut e sombreamentoInteiros e divisão inteiraIndentação e escopoRevisão: reescreva um recibo4Iteração e transformações
Iteração emprestada com forEntradas e enumeratewhile, break e continueIteradores e compreensõesRevisão: crie um ranking2Valores e decisões
Option e NoneIgualdade e identidade de objetosTestes de veracidade e alternativasExpressões if e elifRevisão: regras de elegibilidade3Propriedade e coleções
Vec para listaTuplas e desestruturaçãoHashMap para dictClone e cópias superficiaisRevisão: organizar um inventário6Erros e módulos
Entrada de texto e formataçãoResult, exceções e withMódulos e guarda principalDicas sem verificação de empréstimosRevisão: validar um lote9Projeto: Processamento de Pedidos
Criar o Modelo de PedidoAdicionar Políticas de PreçosPratique por conta própria: Compilador de Python online