Menu
CoddyTech

Port a C Inventory Tool

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

challenge icon

Challenge

Beginner

Implement 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. Its sample prints book:2 then pen:2.

Study the complete C reference below. It uses dynamically allocated decimal strings for exact signed totals, an explicit linked list of entries, and a sorted pointer array for output. The Python implementation uses dict and int instead. Both accept the same well-formed lowercase ASCII name and signed decimal amount records. Allocation failures stop the C reference with an error; no fixed-width amount limit is imposed.

Follow ownership through the reference: each entry owns its name and total. Updating a total allocates a new sum and frees the previous string. The sorted array borrows entry pointers; freeing it does not free the entries. Sorting happens only after all signed changes have been added, so a negative intermediate total is never discarded.

Sample input

3
pen 3
book 2
pen -1

Sample output

book:2
pen:2

C reference (complete inventory.c)

#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* Well-formed input: count, then lowercase-ASCII name and signed decimal amount.
   Totals use owned canonical decimal strings, never fixed-width signed sums. */
static void *allocate(size_t n) {
    void *p = malloc(n);
    if (!p) { fputs("allocation failed\n", stderr); exit(1); }
    return p;
}
static char *copy_text(const char *s) {
    char *p = allocate(strlen(s) + 1);
    strcpy(p, s);
    return p;
}
static char *token(void) {
    int c;
    do { c = getchar(); } while (c != EOF && isspace((unsigned char)c));
    if (c == EOF) return NULL;
    size_t size = 0, capacity = 32;
    char *s = allocate(capacity);
    do {
        if (size + 1 == capacity) {
            if (capacity > (size_t)-1 / 2) exit(1);
            capacity *= 2;
            char *next = realloc(s, capacity);
            if (!next) { free(s); exit(1); }
            s = next;
        }
        s[size++] = (char)c;
        c = getchar();
    } while (c != EOF && !isspace((unsigned char)c));
    s[size] = '\0';
    return s;
}
static const char *magnitude(const char *s) {
    if (*s == '-' || *s == '+') ++s;
    while (*s == '0' && s[1]) ++s;
    return s;
}
static int compare_magnitude(const char *a, const char *b) {
    size_t na = strlen(a), nb = strlen(b);
    if (na != nb) return na < nb ? -1 : 1;
    int order = strcmp(a, b);
    return (order > 0) - (order < 0);
}
static char *combine(const char *left, const char *right) {
    const char *a = magnitude(left), *b = magnitude(right);
    int sa = left[0] == '-' && strcmp(a, "0") != 0 ? -1 : 1;
    int sb = right[0] == '-' && strcmp(b, "0") != 0 ? -1 : 1;
    int order = compare_magnitude(a, b);
    if (sa != sb && order == 0) return copy_text("0");
    int sign = sa;
    if (sa != sb && order < 0) {
        const char *tmp = a; a = b; b = tmp; sign = sb;
    }
    size_t i = strlen(a), j = strlen(b), n = (i > j ? i : j) + 3;
    char *buffer = allocate(n);
    size_t k = n - 1;
    buffer[k] = '\0';
    int carry = 0;
    while (i || j) {
        int x = i ? a[--i] - '0' : 0;
        int y = j ? b[--j] - '0' : 0;
        int digit;
        if (sa == sb) { digit = x + y + carry; carry = digit / 10; digit %= 10; }
        else { digit = x - y - carry; carry = digit < 0; if (carry) digit += 10; }
        buffer[--k] = (char)('0' + digit);
    }
    if (sa == sb && carry) buffer[--k] = (char)('0' + carry);
    while (buffer[k] == '0' && buffer[k + 1]) ++k;
    if (sign < 0 && strcmp(buffer + k, "0") != 0) buffer[--k] = '-';
    char *result = copy_text(buffer + k);
    free(buffer);
    return result;
}
struct Entry { char *name; char *amount; struct Entry *next; };
static int by_name(const void *left, const void *right) {
    const struct Entry *a = *(const struct Entry *const *)left;
    const struct Entry *b = *(const struct Entry *const *)right;
    return strcmp(a->name, b->name);
}
int main(void) {
    char *count = token();
    if (!count) return 1;
    struct Entry *head = NULL;
    /* Decrement decimal count as text as well: no strtol range assumption. */
    while (strcmp(magnitude(count), "0") != 0) {
        char *name = token(), *amount = token();
        if (!name || !amount) return 1;
        struct Entry *entry = head;
        while (entry && strcmp(entry->name, name) != 0) entry = entry->next;
        if (!entry) {
            entry = allocate(sizeof *entry);
            entry->name = name; entry->amount = copy_text("0");
            entry->next = head; head = entry;
        } else free(name);
        char *sum = combine(entry->amount, amount);
        free(entry->amount); free(amount); entry->amount = sum;
        char *remaining = combine(count, "-1"); free(count); count = remaining;
    }
    free(count);
    size_t size = 0;
    for (struct Entry *e = head; e; e = e->next)
        if (e->amount[0] != '-' && strcmp(e->amount, "0") != 0) ++size;
    if (size == 0) puts("empty");
    else {
        if (size > (size_t)-1 / sizeof(struct Entry *)) return 1;
        struct Entry **sorted = allocate(size * sizeof *sorted);
        size_t i = 0;
        for (struct Entry *e = head; e; e = e->next)
            if (e->amount[0] != '-' && strcmp(e->amount, "0") != 0) sorted[i++] = e;
        qsort(sorted, size, sizeof *sorted, by_name);
        for (i = 0; i < size; ++i) printf("%s:%s\n", sorted[i]->name, sorted[i]->amount);
        free(sorted);
    }
    while (head) {
        struct Entry *next = head->next;
        free(head->name); free(head->amount); free(head); head = next;
    }
    return 0;
}

Your code goes in inventory.py. The locked driver.py is the entry file, supplies execution and checks, 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 C Developers

Practice on your own: Online Python compiler