Tracing a loop and a pipeline side by side

A shop applies a 2-dollar discount to every item priced above 5 dollars and totals the discounted prices. Two versions of the code, one procedural and one functional, process the same list of prices.


Python
prices = [5, 8, 2, 9, 6]

# Procedural version
total = 0
for p in prices:
    if p > 5:
        total = total + (p - 2)

# Functional version
total_f = sum(map(lambda p: p - 2, filter(lambda p: p > 5, prices)))


Complete the table with whole numbers. Values of total are in dollars.

QuantityValue
total after the loop processes p = 8
total after the loop processes p = 2
total after the loop processes p = 9
Final value of total from the loop
Number of prices kept by the filter
Largest value produced by the map
Assignments to total in the loop version, counting total = 0

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

More Procedural, Functional, Logical and Object-Oriented Paradigms Questions: