- Courses
- đ»Programming Languages
- đPython
- Functional Programming
- Guided Exercise: E-Commerce Transactions Analysis
On this page
Guided Exercise: Functional Programming in Python
Published on July 6, 2026
By Enrico Hochkoeppler
Web Developer & TutoriaLibre Founder
This guided exercise walks you through a realistic data processing scenario â analysing sales transactions â while applying the functional programming concepts you have learned. Unlike a traditional exercise where you are left to solve problems on your own, this is a guided exercise: you follow along as we build the solution step by step. Each step introduces a new functional programming concept, explains why it is used, and shows the code that solves the problem. By the end, you will have a complete, working solution that demonstrates pure functions, recursion, higherâorder functions, function composition, closures, and currying in a cohesive pipeline.
Exercise Scenarioâ
You are given a dataset of sales transactions from an eâcommerce platform. Each transaction includes the product name, category, quantity sold, unit price, customer name, and purchase date. Your task is to build a data analysis pipeline that:
- Adds a calculated
totalfield to each transaction (quantity * price) - Filters out transactions below a configurable threshold
- Groups transactions by category
- Computes statistics for each category: total revenue, average revenue, and the most expensive product
You will build this solution step by step, applying functional programming techniques at every stage.
The Dataâ
We start with a list of dictionaries representing transactions.
transactions = [
{"product": "Laptop", "category": "Electronics", "quantity": 2, "price": 1200.00, "customer": "Alice", "date": "2025-01-15"},
{"product": "Book", "category": "Books", "quantity": 5, "price": 15.50, "customer": "Bob", "date": "2025-01-16"},
{"product": "Headphones", "category": "Electronics", "quantity": 3, "price": 75.00, "customer": "Alice", "date": "2025-01-17"},
{"product": "Desk", "category": "Furniture", "quantity": 1, "price": 450.00, "customer": "Charlie", "date": "2025-01-18"},
{"product": "Laptop", "category": "Electronics", "quantity": 1, "price": 1200.00, "customer": "Diana", "date": "2025-01-19"},
{"product": "Book", "category": "Books", "quantity": 3, "price": 12.00, "customer": "Eve", "date": "2025-01-20"},
{"product": "Monitor", "category": "Electronics", "quantity": 2, "price": 300.00, "customer": "Frank", "date": "2025-01-21"},
{"product": "Desk", "category": "Furniture", "quantity": 2, "price": 450.00, "customer": "Alice", "date": "2025-01-22"},
{"product": "Book", "category": "Books", "quantity": 2, "price": 20.00, "customer": "Bob", "date": "2025-01-23"},
{"product": "Headphones", "category": "Electronics", "quantity": 1, "price": 75.00, "customer": "Charlie", "date": "2025-01-24"}
]
Part 1: Pure Functionsâ
The first principle of functional programming is to write pure functions â functions that are deterministic and have no side effects. We begin by writing pure functions for data transformation.
Step 1: Calculate the Total Value of a Transactionâ
We need to compute quantity * price for each transaction. This is a pure function because it depends only on its input and produces no side effects.
def transaction_total(transaction):
"""Return the total value of a transaction (quantity * price)."""
return transaction["quantity"] * transaction["price"]
Why this works: This function takes a dictionary, accesses two keys, performs multiplication, and returns the result. It does not modify the input, does not access any global state, and always returns the same value for the same input. This makes it easy to test and reason about.
Step 2: Add a Total Field to a Transactionâ
Instead of modifying the original transaction dictionary, we create a new dictionary with the total field added. This preserves immutability.
def add_total(transaction):
"""Return a new transaction dictionary with a 'total' field added."""
return {**transaction, "total": transaction["quantity"] * transaction["price"]}
Why this works: The {**transaction, "total": ...} syntax creates a new dictionary that includes all keyâvalue pairs from the original plus the new total field. The original dictionary is unchanged. This is a pure function because it produces a new object without mutating the input.
Step 3: Filter Transactions by a Thresholdâ
We need to keep only transactions whose total value is at least a specified threshold. This is another pure function.
def filter_by_threshold(transactions, threshold):
"""Return a list of transactions with total >= threshold."""
return [t for t in transactions if t["total"] >= threshold]
Why this works: This function uses a list comprehension with a conditional expression. It iterates over the input list, checks each transaction's total field against the threshold, and builds a new list containing only the matching transactions. The original list is not modified.
Putting it together: We now have three pure functions. Let's use map() to add totals to all transactions, then use filter_by_threshold() to remove lowâvalue transactions.
from functools import reduce
# Step 1: Add total to each transaction
transactions_with_total = list(map(add_total, transactions))
# Step 2: Filter by threshold
threshold = 100
filtered_transactions = filter_by_threshold(transactions_with_total, threshold)
# View the result
for t in filtered_transactions:
print(f"{t['product']}: ${t['total']:.2f}")
Output:
Laptop: $2400.00
Headphones: $225.00
Desk: $450.00
Laptop: $1200.00
Monitor: $600.00
Desk: $900.00
Notice that transactions with a total below $100 have been removed.
Why we use map() : map() applies a function to every element in an iterable and returns an iterator. It is a higherâorder function that abstracts the iteration pattern, making our code more declarative.
Part 2: Recursionâ
Recursion allows us to process data structures without loops. Here, we use recursion to process nested transaction data.
Step 4: Flatten Nested Transactionsâ
Suppose some transactions contain multiple items. We define a nested data structure:
nested_transactions = [
{"customer": "Alice", "items": [{"product": "Laptop", "price": 1200, "qty": 2}, {"product": "Mouse", "price": 25, "qty": 3}]},
{"customer": "Bob", "items": [{"product": "Book", "price": 15.50, "qty": 5}]},
{"customer": "Charlie", "items": [{"product": "Desk", "price": 450, "qty": 1}, {"product": "Chair", "price": 200, "qty": 2}]}
]
We need to flatten this into a list of individual items. A recursive solution is natural because the nesting can be arbitrarily deep.
def flatten_transactions(nested):
"""Flatten nested transactions into a list of individual items."""
if not nested:
return []
first = nested[0]
customer = first["customer"]
items = first["items"]
# Flatten the items of the first transaction
flattened_items = [
{"customer": customer, "product": item["product"], "price": item["price"], "quantity": item["qty"]}
for item in items
]
# Recursively flatten the rest of the transactions
return flattened_items + flatten_transactions(nested[1:])
Why this works:
- Base case: If the list is empty, return an empty list.
- Recursive case: Process the first transaction in the list. Extract the customer name and iterate over its
itemslist to create a list of flattened item dictionaries. Then recursively process the remaining transactions (from index 1 to the end) and concatenate the results.
The recursion terminates because each call reduces the length of the input list by one.
Step 5: Calculate Total Revenue Recursivelyâ
We can also calculate the total revenue of a flat list of items using recursion.
def total_revenue_recursive(flat_items):
"""Calculate total revenue from a list of flat items."""
if not flat_items:
return 0
first = flat_items[0]
return first["price"] * first["quantity"] + total_revenue_recursive(flat_items[1:])
Why this works:
- Base case: An empty list has total revenue of 0.
- Recursive case: Take the first item, compute its total (
price * quantity), and add it to the total revenue of the rest of the list.
This function is pure because it does not modify any state â it simply computes and returns a value.
# Use the recursive functions
flat = flatten_transactions(nested_transactions)
total = total_revenue_recursive(flat)
print(f"Total revenue: ${total:.2f}")
Output:
Total revenue: $4150.50
Part 3: HigherâOrder Functionsâ
Higherâorder functions take functions as arguments or return them as results. Python's builtâin map(), filter(), and reduce() are classic examples.
Step 6: Group Transactions by Categoryâ
We use itertools.groupby to group transactions by category. groupby requires the data to be sorted by the grouping key.
from itertools import groupby
def group_by_category(transactions):
"""Group transactions by their category field."""
# Sort by category
sorted_transactions = sorted(transactions, key=lambda t: t["category"])
# Group by category
groups = {}
for category, group in groupby(sorted_transactions, key=lambda t: t["category"]):
groups[category] = list(group)
return groups
Why this works:
sorted(transactions, key=lambda t: t["category"])sorts the list by the category field. This is necessary becausegroupbygroups consecutive elements.groupby(sorted_transactions, key=lambda t: t["category"])returns an iterator of(category, group)pairs, where eachgroupis an iterator over the elements in that category.- We convert each group to a list and store it in a dictionary.
Step 7: Compute Category Statisticsâ
We use reduce() to compute the total revenue per category. reduce() applies a function cumulatively to the items of a sequence, reducing it to a single value.
def total_revenue_by_category(transactions):
"""Compute total revenue for each category."""
grouped = group_by_category(transactions)
result = {}
for category, items in grouped.items():
# Use reduce to sum the total field
result[category] = reduce(lambda acc, t: acc + t["total"], items, 0)
return result
Why this works:
- For each category, we call
reduce()with a lambda that adds thetotalfield of each transaction to an accumulator. - The initial accumulator value is
0. reduce()processes each item in the list, adding its total to the accumulator, and returns the final sum.
# Compute total revenue by category
revenue_by_category = total_revenue_by_category(filtered_transactions)
print(revenue_by_category)
Output:
{'Electronics': 5025.0, 'Furniture': 1350.0}
Part 4: Function Compositionâ
Function composition combines multiple functions into a single function. We build a data processing pipeline by composing our pure functions.
Step 8: Define a Composition Helperâ
We define a compose() function that chains functions from right to left, and a pipe() function that chains them from left to right. This is a classic functional programming pattern.
from functools import reduce
def compose(*funcs):
"""Compose functions from right to left."""
def compose_two(f, g):
return lambda x: f(g(x))
return reduce(compose_two, funcs, lambda x: x)
def pipe(*funcs):
"""Compose functions from left to right."""
def pipe_two(f, g):
return lambda x: g(f(x))
return reduce(pipe_two, funcs, lambda x: x)
Why this works:
compose(f, g)returns a function that appliesgfirst, thenf:(f â g)(x) = f(g(x)).pipe(f, g)returns a function that appliesffirst, theng:g(f(x)).- We use
reduce()to apply the composition operator cumulatively across the list of functions. - The identity function (
lambda x: x) serves as the neutral starting value.
Step 9: Build the Pipelineâ
We want a pipeline that:
- Adds a total field to each transaction
- Filters out transactions below a threshold
- Groups by category
- Computes the total revenue per category
def create_pipeline(threshold):
"""Create a data processing pipeline with the given threshold."""
return pipe(
lambda data: list(map(add_total, data)), # Step 1
lambda data: filter_by_threshold(data, threshold), # Step 2
group_by_category, # Step 3
total_revenue_by_category # Step 4
)
Why this works:
pipe()chains the functions from left to right: data flows through each transformation in the order they are listed.- Each function is pure, so the pipeline is a pure function composition.
- The
thresholdis fixed when the pipeline is created, making it reusable for different thresholds.
# Create a pipeline with threshold 100
pipeline = create_pipeline(100)
# Execute the pipeline
result = pipeline(transactions)
print(result)
Output:
{'Electronics': 5025.0, 'Furniture': 1350.0}
Part 5: Closuresâ
Closures allow a function to capture state from its enclosing scope. We use a closure to create a configurable analyser that maintains state.
Step 10: Create an Analyser Factoryâ
We define a factory function that returns a closure with methods for analysing data. The closure captures a threshold and a currency symbol.
def create_analyser(threshold, currency_symbol):
"""Create an analyser closure with configurable threshold and currency."""
# Captured variables
local_threshold = threshold
local_symbol = currency_symbol
# Public methods
def analyse(transactions):
"""Analyse transactions using the configured threshold."""
filtered = filter_by_threshold(transactions, local_threshold)
total = reduce(lambda acc, t: acc + t["total"], filtered, 0)
return f"{local_symbol}{total:.2f}"
def set_threshold(new_threshold):
"""Update the threshold."""
nonlocal local_threshold
local_threshold = new_threshold
def get_threshold():
"""Get the current threshold."""
return local_threshold
def set_symbol(new_symbol):
"""Update the currency symbol."""
nonlocal local_symbol
local_symbol = new_symbol
# Return a dictionary of functions (a closure)
return {
"analyse": analyse,
"set_threshold": set_threshold,
"get_threshold": get_threshold,
"set_symbol": set_symbol
}
Why this works:
- The
create_analyserfunction defineslocal_thresholdandlocal_symbolin its scope. - The nested functions
analyse,set_threshold,get_threshold, andset_symbolcapture these variables through closures. - The
nonlocalkeyword inset_thresholdandset_symbolallows these nested functions to modify the captured variables. - The returned dictionary provides controlled access to the closure's state.
Step 11: Use the Analyserâ
# Create an analyser with threshold 100 and currency symbol '$'
analyser = create_analyser(100, "$")
# Analyse the transactions
print(analyser["analyse"](transactions)) # Output: $5988.50
# Change the threshold to 200
analyser["set_threshold"](200)
print(analyser["analyse"](transactions)) # Output: $5850.00
# Change the currency symbol
analyser["set_symbol"]("âŹ")
print(analyser["analyse"](transactions)) # Output: âŹ5850.00
Why this works: The closure maintains state across calls. When set_threshold is called, it updates the captured local_threshold variable, and subsequent calls to analyse use the new value. The state is encapsulated and cannot be accessed directly â only through the provided methods.
Part 6: Curryingâ
Currying transforms a function that takes multiple arguments into a sequence of functions that each take a single argument. This enables partial application and function specialisation.
Step 12: Curry a Discount Functionâ
We define a generalâpurpose curry() decorator, then apply it to a discount calculation function.
def curry(func):
"""Transform a function into a curried function."""
def curried(*args):
# If enough arguments are provided, call the function
if len(args) >= func.__code__.co_argcount:
return func(*args)
# Otherwise, return a new function that captures the arguments
return lambda *more: curried(*(args + more))
return curried
@curry
def apply_discount(rate, total):
"""Apply a discount rate to a total."""
return total * (1 - rate)
Why this works:
- The
currydecorator checks how many arguments the original function expects usingfunc.__code__.co_argcount. - If enough arguments are provided, it calls the original function.
- If fewer arguments are provided, it returns a new function that captures the provided arguments and waits for more.
Step 13: Create Specialised Discount Functionsâ
With the curried apply_discount, we can create specialised functions by fixing the discount rate.
# Create specialised discount functions
ten_percent_off = apply_discount(0.10)
twenty_percent_off = apply_discount(0.20)
# Apply discounts
original_total = 1200.00
print(ten_percent_off(original_total)) # 1080.0
print(twenty_percent_off(original_total)) # 960.0
Why this works: apply_discount(0.10) returns a new function that expects a total argument. This returned function is a closure that captures the discount rate and applies it when called.
Step 14: Apply Discounts to the Datasetâ
We can use the specialised discount functions with map() to apply discounts to all transaction totals.
# Get all totals from the filtered transactions
totals = [t["total"] for t in filtered_transactions]
# Apply a 10% discount to all totals
discounted_totals = list(map(ten_percent_off, totals))
print(discounted_totals)
Output:
[2160.0, 202.5, 405.0, 1080.0, 540.0, 810.0]
Part 7: Capstone â Complete Functional Pipelineâ
We now bring everything together into a complete, functional data analysis pipeline.
Step 15: Define All Pure Functionsâ
We define all the pure functions we have built: add_total, filter_by_threshold, group_by_category, and aggregate_category.
from itertools import groupby
from functools import reduce
def add_total(transaction):
"""Add a total field to a transaction."""
return {**transaction, "total": transaction["quantity"] * transaction["price"]}
def filter_by_threshold(transactions, threshold):
"""Filter transactions by total threshold."""
return [t for t in transactions if t["total"] >= threshold]
def group_by_category(transactions):
"""Group transactions by category."""
sorted_t = sorted(transactions, key=lambda t: t["category"])
groups = {}
for category, group in groupby(sorted_t, key=lambda t: t["category"]):
groups[category] = list(group)
return groups
def aggregate_category(items):
"""Aggregate statistics for a category."""
total_revenue = reduce(lambda acc, t: acc + t["total"], items, 0)
avg_revenue = total_revenue / len(items) if items else 0
most_expensive = max(items, key=lambda t: t["total"])
return {
"total_revenue": total_revenue,
"average_revenue": avg_revenue,
"most_expensive_product": most_expensive["product"],
"most_expensive_total": most_expensive["total"]
}
def aggregate_all_categories(groups):
"""Aggregate statistics for all categories."""
return {category: aggregate_category(items) for category, items in groups.items()}
Step 16: Compose the Complete Pipelineâ
We use pipe() to compose the complete pipeline.
def analyse_sales(transactions, threshold):
"""Complete sales analysis pipeline."""
pipeline = pipe(
lambda data: list(map(add_total, data)),
lambda data: filter_by_threshold(data, threshold),
group_by_category,
aggregate_all_categories
)
return pipeline(transactions)
Why this works:
- The pipeline is a composition of pure functions.
- Data flows from left to right through each transformation.
- Each function is independent and testable in isolation.
Step 17: Execute the Pipelineâ
# Run the analysis with threshold 100
result = analyse_sales(transactions, 100)
print(result)
Expected output:
{
'Electronics': {
'total_revenue': 5025.0,
'average_revenue': 838.33,
'most_expensive_product': 'Laptop',
'most_expensive_total': 2400.0
},
'Furniture': {
'total_revenue': 1350.0,
'average_revenue': 675.0,
'most_expensive_product': 'Desk',
'most_expensive_total': 900.0
}
}
Summary of Concepts Practicedâ
ConceptStepExplanationPure functions1, 2, 3, 15Functions that are deterministic and have no side effectsRecursion4, 5Processing nested data structures with recursive callsHigherâorder functions6, 7Using map(), filter(), reduce(), and groupbyFunction composition8, 9, 16Combining functions with compose() and pipe()Closures10, 11Functions that capture and maintain state from enclosing scopesCurrying12, 13, 14Transforming multiâargument functions into chains of unary functions
Running the Complete Codeâ
Here is the complete, runnable code for the entire guided exercise. You can copy and paste it into a Python file or interactive environment to follow along.
from itertools import groupby
from functools import reduce
# ============================================================================
# DATA
# ============================================================================
transactions = [
{"product": "Laptop", "category": "Electronics", "quantity": 2, "price": 1200.00, "customer": "Alice", "date": "2025-01-15"},
{"product": "Book", "category": "Books", "quantity": 5, "price": 15.50, "customer": "Bob", "date": "2025-01-16"},
{"product": "Headphones", "category": "Electronics", "quantity": 3, "price": 75.00, "customer": "Alice", "date": "2025-01-17"},
{"product": "Desk", "category": "Furniture", "quantity": 1, "price": 450.00, "customer": "Charlie", "date": "2025-01-18"},
{"product": "Laptop", "category": "Electronics", "quantity": 1, "price": 1200.00, "customer": "Diana", "date": "2025-01-19"},
{"product": "Book", "category": "Books", "quantity": 3, "price": 12.00, "customer": "Eve", "date": "2025-01-20"},
{"product": "Monitor", "category": "Electronics", "quantity": 2, "price": 300.00, "customer": "Frank", "date": "2025-01-21"},
{"product": "Desk", "category": "Furniture", "quantity": 2, "price": 450.00, "customer": "Alice", "date": "2025-01-22"},
{"product": "Book", "category": "Books", "quantity": 2, "price": 20.00, "customer": "Bob", "date": "2025-01-23"},
{"product": "Headphones", "category": "Electronics", "quantity": 1, "price": 75.00, "customer": "Charlie", "date": "2025-01-24"}
]
nested_transactions = [
{"customer": "Alice", "items": [{"product": "Laptop", "price": 1200, "qty": 2}, {"product": "Mouse", "price": 25, "qty": 3}]},
{"customer": "Bob", "items": [{"product": "Book", "price": 15.50, "qty": 5}]},
{"customer": "Charlie", "items": [{"product": "Desk", "price": 450, "qty": 1}, {"product": "Chair", "price": 200, "qty": 2}]}
]
# ============================================================================
# PURE FUNCTIONS
# ============================================================================
def transaction_total(transaction):
return transaction["quantity"] * transaction["price"]
def add_total(transaction):
return {**transaction, "total": transaction["quantity"] * transaction["price"]}
def filter_by_threshold(transactions, threshold):
return [t for t in transactions if t["total"] >= threshold]
def group_by_category(transactions):
sorted_t = sorted(transactions, key=lambda t: t["category"])
groups = {}
for category, group in groupby(sorted_t, key=lambda t: t["category"]):
groups[category] = list(group)
return groups
def aggregate_category(items):
total_revenue = reduce(lambda acc, t: acc + t["total"], items, 0)
avg_revenue = total_revenue / len(items) if items else 0
most_expensive = max(items, key=lambda t: t["total"])
return {
"total_revenue": total_revenue,
"average_revenue": avg_revenue,
"most_expensive_product": most_expensive["product"],
"most_expensive_total": most_expensive["total"]
}
def aggregate_all_categories(groups):
return {category: aggregate_category(items) for category, items in groups.items()}
# ============================================================================
# RECURSION
# ============================================================================
def flatten_transactions(nested):
if not nested:
return []
first = nested[0]
customer = first["customer"]
items = first["items"]
flattened_items = [
{"customer": customer, "product": item["product"], "price": item["price"], "quantity": item["qty"]}
for item in items
]
return flattened_items + flatten_transactions(nested[1:])
def total_revenue_recursive(flat_items):
if not flat_items:
return 0
first = flat_items[0]
return first["price"] * first["quantity"] + total_revenue_recursive(flat_items[1:])
# ============================================================================
# FUNCTION COMPOSITION
# ============================================================================
def compose(*funcs):
def compose_two(f, g):
return lambda x: f(g(x))
return reduce(compose_two, funcs, lambda x: x)
def pipe(*funcs):
def pipe_two(f, g):
return lambda x: g(f(x))
return reduce(pipe_two, funcs, lambda x: x)
# ============================================================================
# CLOSURES
# ============================================================================
def create_analyser(threshold, currency_symbol):
local_threshold = threshold
local_symbol = currency_symbol
def analyse(transactions):
filtered = filter_by_threshold(transactions, local_threshold)
total = reduce(lambda acc, t: acc + t["total"], filtered, 0)
return f"{local_symbol}{total:.2f}"
def set_threshold(new_threshold):
nonlocal local_threshold
local_threshold = new_threshold
def get_threshold():
return local_threshold
def set_symbol(new_symbol):
nonlocal local_symbol
local_symbol = new_symbol
return {
"analyse": analyse,
"set_threshold": set_threshold,
"get_threshold": get_threshold,
"set_symbol": set_symbol
}
# ============================================================================
# CURRYING
# ============================================================================
def curry(func):
def curried(*args):
if len(args) >= func.__code__.co_argcount:
return func(*args)
return lambda *more: curried(*(args + more))
return curried
@curry
def apply_discount(rate, total):
return total * (1 - rate)
# ============================================================================
# COMPLETE PIPELINE
# ============================================================================
def analyse_sales(transactions, threshold):
pipeline = pipe(
lambda data: list(map(add_total, data)),
lambda data: filter_by_threshold(data, threshold),
group_by_category,
aggregate_all_categories
)
return pipeline(transactions)
# ============================================================================
# DEMONSTRATION
# ============================================================================
if __name__ == "__main__":
print("=" * 60)
print("DEMONSTRATION")
print("=" * 60)
# Pure functions and map/filter
print("\n--- Pure Functions ---")
transactions_with_total = list(map(add_total, transactions))
filtered = filter_by_threshold(transactions_with_total, 100)
print("Filtered transactions (total >= 100):")
for t in filtered:
print(f" {t['product']}: ${t['total']:.2f}")
# Recursion
print("\n--- Recursion ---")
flat = flatten_transactions(nested_transactions)
print("Flattened nested transactions:")
for item in flat:
print(f" {item['customer']}: {item['product']} x{item['quantity']}")
total = total_revenue_recursive(flat)
print(f"Total revenue from nested transactions: ${total:.2f}")
# Function composition
print("\n--- Function Composition (Pipeline) ---")
pipeline = create_pipeline(100)
result = pipeline(transactions)
print("Pipeline result (threshold = 100):")
for category, stats in result.items():
print(f" {category}: ${stats['total_revenue']:.2f}")
# Closures
print("\n--- Closures (Analyser Factory) ---")
analyser = create_analyser(100, "$")
print(f"Analyse with threshold 100: {analyser['analyse'](transactions)}")
analyser['set_threshold'](200)
print(f"Analyse with threshold 200: {analyser['analyse'](transactions)}")
analyser['set_symbol']("âŹ")
print(f"Analyse with threshold 200 and ⏠symbol: {analyser['analyse'](transactions)}")
# Currying
print("\n--- Currying ---")
ten_percent_off = apply_discount(0.10)
print(f"10% off $1200: ${ten_percent_off(1200):.2f}")
# Complete pipeline
print("\n--- Complete Functional Pipeline ---")
final_result = analyse_sales(transactions, 100)
print("Complete analysis result:")
for category, stats in final_result.items():
print(f" {category}:")
print(f" Total revenue: ${stats['total_revenue']:.2f}")
print(f" Average revenue: ${stats['average_revenue']:.2f}")
print(f" Most expensive product: {stats['most_expensive_product']} (${stats['most_expensive_total']:.2f})")
Conclusionâ
You have now completed a guided exercise that applies the core concepts of functional programming in Python. The solution demonstrates:
- Pure functions for deterministic, sideâeffectâfree transformations
- Recursion for processing nested data structures
- Higherâorder functions (
map,filter,reduce,groupby) for data transformation - Function composition for building declarative data pipelines
- Closures for encapsulating state in factory functions
- Currying for creating specialised functions through partial application
The complete, runnable code is provided so you can experiment with it, modify the thresholds, add new transformations, and deepen your understanding of functional programming in Python.
Found this helpful? Share the knowledge...
... or support this project to keep it alive!
Previous
Lazy Evaluation
Next
Advanced Python
-
Exercise Scenario
-
The Data
-
Part 1: Pure Functions
- Step 1: Calculate the Total Value of a Transaction
- Step 2: Add a Total Field to a Transaction
- Step 3: Filter Transactions by a Threshold
-
Part 2: Recursion
- Step 4: Flatten Nested Transactions
- Step 5: Calculate Total Revenue Recursively
-
Part 3: HigherâOrder Functions
- Step 6: Group Transactions by Category
- Step 7: Compute Category Statistics
-
Part 4: Function Composition
- Step 8: Define a Composition Helper
- Step 9: Build the Pipeline
-
Part 5: Closures
- Step 10: Create an Analyser Factory
- Step 11: Use the Analyser
-
Part 6: Currying
- Step 12: Curry a Discount Function
- Step 13: Create Specialised Discount Functions
- Step 14: Apply Discounts to the Dataset
-
Part 7: Capstone â Complete Functional Pipeline
- Step 15: Define All Pure Functions
- Step 16: Compose the Complete Pipeline
- Step 17: Execute the Pipeline
-
Summary of Concepts Practiced
-
Running the Complete Code
-
Conclusion
