Port a Dart Inventory
Lesson 47 of 48 in Coddy's Python for Dart Developers course.
Challenge
BeginnerPort 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
1From Dart to Python
Run Your First Python ProgramInterpolation and printvar, final, and Python NamesFloor Versus TruncationBraces and Block ScopeRecap: Rewrite a Receipt4Iteration and Transformations
for-in and rangeentries and enumerateLoop Updates and continuewhere, map, and List BuildingRecap: Build a Ranking2Values and Decisions
Null Safety and NoneList Equality ChangesConditions and Null DefaultsTernaries and elifRecap: Eligibility Rules3Collections and References
Lists and Negative IndexesRecords and Tuple UnpackingMap Lookups and KeyErrorSets and Shared ObjectsRecap: Clean an Inventory6Reliable Python Programs
stdin and Exact Formattingon, catch, finally, and withLibraries and Import ExecutionStatic Types Versus HintsRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler