Menu
CoddyTech

Port a Ruby Inventory

Lesson 47 of 48 in Coddy's Python for Ruby Developers course.

challenge icon

Challenge

Beginner

Port 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)
end

Try it yourself

from inventory import inventory

lines = [input() for _ in range(int(input()))]
print(inventory(lines))

All lessons in Python for Ruby Developers

Practice on your own: Online Python compiler