Menu
CoddyTech

Port a Dart Inventory

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

challenge icon

Challenge

Beginner

Port the complete Dart inventory reference below. Implement inventory(lines) in editable inventory.py; it receives well-formed name amount strings with nonempty lowercase ASCII names and signed decimal integer amounts. Sum all updates per name, retaining negative intermediate totals. After aggregation, keep positive totals and sort names ascending. Return name:total lines joined with newlines, or empty if none remain. Return text without a trailing newline. The locked driver.py reads a nonnegative count followed by that many records and prints your returned string with a final newline.

Dart uses Map<String, BigInt>, null-coalescing lookup, a filtered sorted key list, and explicit return values. Python uses arbitrary-precision int and dict.get instead. Do not filter updates before aggregation. For pen 3, book 2, pen -1, output is book:2 then pen:2. The Dart source uses native standard input for its standalone entry point.

Dart reference

import 'dart:io';
String inventory(List<String> lines) {
  final stock = <String, BigInt>{};
  for (final line in lines) {
    final parts = line.trim().split(RegExp(r'\s+'));
    final name = parts[0];
    stock[name] = (stock[name] ?? BigInt.zero) + BigInt.parse(parts[1]);
  }
  final names = stock.keys.where((name) => stock[name]! > BigInt.zero).toList()..sort();
  if (names.isEmpty) return 'empty';
  return names.map((name) => '$name:${stock[name]}').join('\n');
}
void main() {
  final count = int.parse(stdin.readLineSync()!);
  final lines = List<String>.generate(count, (_) => stdin.readLineSync()!);
  print(inventory(lines));
}

Try it yourself

from inventory import inventory

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

All lessons in Python for Dart Developers

Practice on your own: Online Python compiler