Problem overview
Version 6 of the cart groups items by category. Three parallel lists describe the cart: items, prices and categories, where position i in each list describes the same item. The program adds up the prices within each category and stores one row per category in result, sorted alphabetically by category name.
For the starting data, the clothes cost 25 + 40 and the food costs 2 + 3 + 1:
Clothes: $65
Food: $6
The list order doesn't decide the row order: "Food" appears first in the data, but "Clothes" comes first in the output.
Approach: accumulate in a dictionary, then sort the keys
The categories aren't known in advance, so the program can't create one variable per category. A dictionary named totals fits: its keys are the category names that have appeared, and each value is the sum so far. The loop adds each item's price to its category's entry.
A dictionary hands back its keys in the order they were first inserted, which is not alphabetical. The second half of the program therefore sorts the keys and builds one row for each, then joins the rows.
Step by step
- Create the empty dictionary
totals. It starts with no categories. - Loop over positions.
for i in range(len(items))visits every item by its index, so the sameican readcategoriesandprices. - Read the category.
cat = categories[i]names this item's group. - Add the price.
totals[cat] = totals.get(cat, 0) + prices[i]. For a category seen for the first time,getsupplies 0, so the entry starts at the item's price. - Create the empty list
lines. This happens after the loop, so every total is final. - Loop over the sorted keys.
sorted(totals)returns the dictionary's keys as a list in alphabetical order. - Append each category's row. The category, a colon, a space, a dollar sign and its total as text.
- Join the rows with a newline between each two.
Here is how totals grows during the first loop, one pass per line:
0 Apple Food {'Food': 2}
1 Bread Food {'Food': 5}
2 Shirt Clothes {'Food': 5, 'Clothes': 25}
3 Banana Food {'Food': 6, 'Clothes': 25}
4 Pants Clothes {'Food': 6, 'Clothes': 65}
After the loop, sorted(totals) is ['Clothes', 'Food'].
The solution in Python
items = ["Apple", "Bread", "Shirt", "Banana", "Pants"]
prices = [2, 3, 25, 1, 40]
categories = ["Food", "Food", "Clothes", "Food", "Clothes"]
totals = {}
for i in range(len(items)):
cat = categories[i]
totals[cat] = totals.get(cat, 0) + prices[i]
lines = []
for cat in sorted(totals):
lines.append(cat + ": $" + str(totals[cat]))
result = "\n".join(lines)
Details worth knowing:
- The
getdefault does the first-time work. Without it,totals[cat]would raise aKeyErrorfor a category that has no entry yet. The default 0 means "nothing added so far", so no separateif cat in totalsis needed. - Iterating a dictionary gives its keys.
sorted(totals)is the same assorted(totals.keys()). It returns a new list and leaves the dictionary untouched. - A dictionary can't be sorted in place. It remembers insertion order, so
totalsstill listsFoodbeforeClothesafter the program runs. Only the list of keys is sorted. - Two loops, two jobs. The first collects, the second reports. Keeping them separate means the rows are written once per category, not once per item.
- Strings are sorted by character code. That is alphabetical for names that start the same way, but not for mixed case.
Edge cases and common mistakes
- Uppercase sorts before lowercase. With categories
["food", "Toys", "Food"]and prices 1, 2 and 3, the rows areFood: $3,Toys: $2andfood: $1. Capitalisation also makesfoodandFoodtwo different categories. - An empty cart. With empty lists the loop never runs, no rows are added and
resultis the empty string''. - Replacing instead of adding.
totals[cat] = prices[i]would keep only the last price of each category. - Using
totals[cat] += prices[i]on a new key. It raises aKeyErrorthe first time a category appears. - Appending rows inside the first loop. The program would write a row for every item with a partial total.
- Forgetting
str(). A total is an integer, so it has to be converted before it joins the text.
Testing
- The starting lists give
Clothes: $65andFood: $6. ["A", "B", "C"],[1, 2, 3]and["food", "Toys", "Food"]giveFood: $3,Toys: $2andfood: $1.- Three empty lists give an empty
result.
