SECTION 24 / 31

Count food rows for each customer, then find the maximum

1 min read
Ahmed’s three food bills contribute 8+7+3=18 Food rows. His non-food bill contributes zero.
Ahmed’s three food bills contribute 8+7+3=18 Food rows. His non-food bill contributes zero.
REAL COURSE DATA · KEYS, COUNTS AND CONNECTIONS

Accumulate food item rows by customer or shop

Follow the dictionary as its keys and values change. Predict each lookup or update before revealing the next step.

Ready

CURRENT RECORD / VALUE

Ready to begin

No records have been processed. Start with Next step.

What we remember

Processed
0

Predict the next key, whether it already exists, and the value that will be stored.

foodD = {}
foreach bill in bills {
    customer = bill.Customer
    foreach item in bill.Items {
        if (broadCategory(item.Category) == "Food") {
            if (isKey(foodD,customer)) {
                foodD[customer] = foodD[customer] + 1
            }
            else {
                foodD[customer] = 1
            }
        }
    }
}

The source’s foodD creates a customer key only when a Food row occurs. A different valid representation creates every observed customer with zero first; the key sets differ when someone has no Food row, while qualifying Food totals agree. In these supplied bills, all 16 customers have at least one Food row.

Complete the source’s unstated maximum phase by scanning keys(foodD). Keep the best count and a list of every customer tied at that count. Initialize safely from the first entry or use a flag for “no entries yet”. Here Ahmed is highest with 18; Akshaya has 13 and Srivatsan 12. Sorting can show a full ranking but is unnecessary to find a maximum.

Try it yourself

Does a customer’s non-food bill erase their Food total?

Show explained answer

No. Skip non-food rows without replacing the accumulated value.

Try it yourself

What is Ahmed’s observed Food row total?

Show explained answer

18, from bills 18,20,29 with 8,7,3 Food rows.

Try it yourself

Why keep a list of winners?

Show explained answer

Several customers could tie for the largest value; recording only the last one would lose other winners.

YOUR STUDY PROGRESS

Finished this section? Save your progress.

Back to top ↑