Port a GDScript Inventory
Lesson 47 of 48 in Coddy's Python for GDScript Developers course.
Challenge
BeginnerPort the GDScript reference below. Implement inventory(lines) in inventory.py, returning text without a trailing newline. Each well-formed record has a nonempty lowercase ASCII name and a signed base-ten integer amount separated by whitespace. Sum every update, including negative intermediate totals. After aggregation, discard totals of zero or less. Sort positive entries by name and join name:total lines with newlines, or return empty when no positive totals remain. The locked driver.py reads a nonnegative count and that many records and prints the returned string with a final newline.
The GDScript reference uses a Dictionary, key sorting, PackedStringArray joining, and decimal-string arithmetic to avoid the signed 64-bit int limit. Python int handles the totals directly, so do not port those arithmetic helpers. This headless SceneTree reads records and quits; your Python function receives records from its locked driver. Aggregate before filtering, since a negative update can later recover.
GDScript reference
extends SceneTree
# Decimal strings avoid Godot int overflow for arbitrary inventory totals.
func normalize_amount(text):
var negative = text.begins_with("-")
var digits = text
if digits.begins_with("-") or digits.begins_with("+"):
digits = digits.substr(1)
while digits.length() > 1 and digits.begins_with("0"):
digits = digits.substr(1)
return "-" + digits if negative and digits != "0" else digits
func compare_magnitude(a, b):
if a.length() != b.length():
return -1 if a.length() < b.length() else 1
if a == b:
return 0
return -1 if a < b else 1
func add_magnitude(a, b):
var i = a.length() - 1
var j = b.length() - 1
var carry = 0
var out = ""
while i >= 0 or j >= 0 or carry != 0:
var total = carry
if i >= 0:
total += int(a[i])
i -= 1
if j >= 0:
total += int(b[j])
j -= 1
out = str(total % 10) + out
carry = int(total / 10.0)
return out
# Requires a >= b in magnitude.
func subtract_magnitude(a, b):
var i = a.length() - 1
var j = b.length() - 1
var borrow = 0
var out = ""
while i >= 0:
var digit = int(a[i]) - borrow
i -= 1
if j >= 0:
digit -= int(b[j])
j -= 1
borrow = 1 if digit < 0 else 0
out = str(digit + 10 * borrow) + out
return normalize_amount(out)
func add_amount(left, right):
left = normalize_amount(left)
right = normalize_amount(right)
var ln = left.begins_with("-")
var rn = right.begins_with("-")
var a = left.substr(1) if ln else left
var b = right.substr(1) if rn else right
if ln == rn:
return normalize_amount(("-" if ln else "") + add_magnitude(a, b))
var order = compare_magnitude(a, b)
if order == 0:
return "0"
if order > 0:
return normalize_amount(("-" if ln else "") + subtract_magnitude(a, b))
return normalize_amount(("-" if rn else "") + subtract_magnitude(b, a))
func inventory(lines):
var stock = {}
var whitespace = RegEx.new()
whitespace.compile("\\s+")
for line in lines:
var fields = whitespace.sub(line.strip_edges(), " ", true).split(" ", false)
var name = fields[0]
stock[name] = add_amount(stock.get(name, "0"), fields[1])
var names = stock.keys()
names.sort()
var report = PackedStringArray()
for name in names:
var amount = stock[name]
if amount != "0" and not amount.begins_with("-"):
report.append(name + ":" + amount)
return "empty" if report.is_empty() else "\n".join(report)
func _init():
var count = int(OS.read_string_from_stdin())
var lines = []
for _i in range(count):
lines.append(OS.read_string_from_stdin())
print(inventory(lines))
quit()Your code goes in inventory.py. The locked driver.py supplies input/output and cannot be edited.
Try it yourself
from inventory import inventory
lines = [input() for _ in range(int(input()))]
print(inventory(lines))
All lessons in Python for GDScript Developers
1From GDScript to Python
Run Your First Python ProgramPrint Is Not printsVar, Const, and BindingsInteger Division DifferencesSimilar Indentation, New ScopeRecap: Rewrite a Receipt4Iteration and Transformations
Ranges and RebindingItems and enumerateWhile and Early ExitArray Callbacks and KeysRecap: Build a Ranking2Values and Decisions
Null and NoneThe is Keyword Changes MeaningLogical Results and OperandsConditional ExpressionsRecap: Eligibility Rules3Collections and Shared State
Array and List APIsArrays, Vectors, and TuplesDictionary Lookup RulesDuplicate and Shallow CopyRecap: Clean an Inventory6Input, Errors, and Modules
Console Work Outside GodotValidation and ExceptionsScript Resources and ImportsTyped GDScript and AnnotationsRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler