Port a Go Inventory Tool
Lesson 47 of 48 in Coddy's Python for Go Developers course.
Challenge
BeginnerImplement inventory(lines) in inventory.py; do not read standard input or print in this function. It receives well-formed name amount record strings, with nonempty lowercase ASCII names and signed integer amounts. Sum all changes by name, retaining negative intermediate totals. Only after aggregation discard totals <= 0. Return positive entries as name:total in ascending name order, joined by newlines without a trailing newline; return empty if none remain. The locked driver reads a nonnegative count and that many records, calls your function, and prints its result with a final newline. Match the Go reference below using Python dict and int instead of map[string]*big.Int. Its sample input 3 followed by pen 3, book 2, and pen -1 prints book:2 then pen:2. Its sample prints book:2 then pen:2.
Editable files: inventory.py. Keep the provided imports and the required API names. The locked driver.py supplies execution and checks; do not edit it.
Go reference: complete program
This program reads the same count and record lines as the Python driver. math/big.Int preserves the unrestricted signed-integer contract. Go maps have no sorted iteration guarantee, so keys are explicitly sorted. Add mutates its receiver; each key owns a separate accumulator.
package main
import (
"bufio"
"fmt"
"io"
"math/big"
"os"
"sort"
"strconv"
"strings"
)
func inventory(lines []string) string {
stock := make(map[string]*big.Int)
for _, line := range lines {
fields := strings.Fields(line)
amount, ok := new(big.Int).SetString(fields[1], 10)
if !ok { panic("input contract requires an integer") }
if stock[fields[0]] == nil { stock[fields[0]] = new(big.Int) }
stock[fields[0]].Add(stock[fields[0]], amount)
}
names := make([]string, 0, len(stock))
for name, amount := range stock {
if amount.Sign() > 0 { names = append(names, name) }
}
sort.Strings(names)
result := make([]string, 0, len(names))
for _, name := range names { result = append(result, name+":"+stock[name].String()) }
if len(result) == 0 { return "empty" }
return strings.Join(result, "\n")
}
func main() {
reader := bufio.NewReader(os.Stdin)
first, err := reader.ReadString('\n')
if err != nil && err != io.EOF { panic(err) }
count, err := strconv.Atoi(strings.TrimSpace(first))
if err != nil || count < 0 { panic("input contract requires a nonnegative count") }
lines := make([]string, 0, count)
for i := 0; i < count; i++ {
line, err := reader.ReadString('\n')
if err != nil && err != io.EOF { panic(err) }
lines = append(lines, strings.TrimSuffix(line, "\n"))
}
fmt.Println(inventory(lines))
}Try it yourself
from inventory import inventory
lines = [input() for _ in range(int(input()))]
print(inventory(lines))
All lessons in Python for Go Developers
1From Go to Python
Run Your First Python ProgramPrinting, Quotes, and CommentsBindings Beyond Go TypesDivision and Growing IntegersIndentation and ScopeRecap: A Python Receipt4Iteration and Transformations
range and Value IterationIndexes and Map EntriesSentinels Without Truth TrapsComprehensions and Stable SortRecap: Stable Ranking2Values, Absence, and Branches
None, nil, and Zero ValuesEquality Is Not IdentityTruth Tests Beyond boolBranches and Value SelectionRecap: Missing or Eligible3Slices, Maps, and Sharing
Slices Versus Python ListsMultiple Values and TuplesGo Maps and Python dictsSets and Shallow CopiesRecap: Inventory Collections6Errors, Modules, and Hints
Text and Exact OutputErrors Versus ExceptionsPackages and Module ExecutionHints Versus Static TypesRecap: Validate a Batch9Project: An Order Processor
Project: Model an OrderProject: Pricing PoliciesPractice on your own: Online Python compiler