Port a Ruby Inventory
Lesson 47 of 48 in Coddy's Python for Ruby Developers course.
Challenge
BeginnerPort the complete Ruby reference below. Implement inventory(lines) in editable inventory.py; it receives well-formed name amount strings and returns output text without a trailing newline. Names contain nonempty lowercase ASCII letters; amounts are signed decimal integers. Sum all updates by name, retaining negative intermediate totals. After aggregation, keep only positive totals and sort names in ascending order. Return name:total lines joined by newlines, or empty when none remain. Do not read input or print inside your function. The locked driver.py reads a nonnegative count and that many records, then prints your returned text with a final newline.
The Ruby reference uses Hash.new(0), each, select, and map, with an implicit method return. Python needs an explicit dictionary fallback, explicit return, and explicit sorting. Both languages support arbitrary-size integer totals. For pen 3, book 2, pen -1, the result is book:2 followed by pen:2.
Ruby reference
def inventory(lines)
stock = Hash.new(0)
lines.each do |line|
name, amount = line.split
stock[name] += Integer(amount, 10)
end
names = stock.keys.select { |name| stock[name] > 0 }.sort
names.empty? ? 'empty' : names.map { |name| "#{name}:#{stock[name]}" }.join("\n")
end
if $PROGRAM_NAME == __FILE__
count = Integer(STDIN.gets, 10)
lines = Array.new(count) { STDIN.gets.chomp }
puts inventory(lines)
endTry it yourself
from inventory import inventory
lines = [input() for _ in range(int(input()))]
print(inventory(lines))
All lessons in Python for Ruby Developers
1From Ruby to Python
Run Your First Python ProgramStrings and InterpolationNames and Mutable StringsDivision and ParsingFrom end to IndentationRecap: Rewrite a Receipt4Iteration and Transformations
each and Python foreach_pair and enumeratenext Becomes continueselect, map, and sort_byRecap: Build a Ranking2Values and Decisions
nil Becomes None== and equal?Zero Is False in Pythonelsif and Conditional ValuesRecap: Eligibility Rules3Collections and References
Array Methods and ListsParallel Assignment and TuplesHash Defaults and Dict Keysdup, Copies, and SetsRecap: Clean an Inventory6Reliable Python Programs
gets, input, and Formattingrescue and Context Managersrequire and Import GuardsHints Do Not Enforce TypesRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler