Examples and technical help
This page collects small technical examples that are useful for homework reports, experiments, timing, plotting, and file handling.
Python lists, arrays, and memory
Python lists are flexible, but they are not the same as low-level C-style arrays. In CPython, a list is implemented as a dynamic array of references to Python objects. This makes lists convenient, but the list normally stores references rather than raw numeric values.
For algorithmic thinking, it is useful to distinguish:
- a conceptual array: consecutive indexed positions;
- a Python list: a dynamic sequence of object references;
array.array: compact storage for basic numeric types;- a NumPy array: compact, vectorised storage for larger numeric experiments.
Useful references:
- Python tutorial: data structures
- Python
arraymodule - NumPy array creation
- Introductory comparison of Python arrays and lists
Google Colab: downloading files
Files created in Colab remain in the temporary Colab session until you download them or copy them to persistent storage.
from google.colab import files
files.download("example_file.csv")
Measuring running time
For timing experiments, prefer time.perf_counter() over time.time(). Measure only the operation you want to study, generate inputs outside the measured region, repeat every case, and retain every raw measurement.
The Algorithmics timing experiment demo provides a complete reusable notebook structure.
The following smaller example is directly runnable. Replace the example methods and input sizes with those required by the homework.
from time import perf_counter
import random
import pandas as pd
methods = {
"linear_sum": sum,
"library_sort": sorted,
}
results = []
sizes = [1_000, 10_000, 100_000, 1_000_000]
trials = 7
for n in sizes:
for method_name, method in methods.items():
for trial in range(trials):
seed = 2026 + trial
random.seed(seed)
data = list(range(n))
random.shuffle(data)
start = perf_counter()
result = method(data)
elapsed = perf_counter() - start
results.append({
"n": n,
"method": method_name,
"seed": seed,
"trial": trial,
"time_seconds": elapsed,
})
df = pd.DataFrame(results)
df.to_csv("hw_results.csv", index=False)
df.head()
Use the same generated input for methods that you compare directly. If a method modifies its input, create the required fresh copy before starting the timer and document that choice.
Summarising and plotting results
Keep the raw measurements and calculate a compact summary separately. Median is usually more robust to occasional slow trials than the arithmetic mean. Minimum and maximum provide a simple view of variability; other tasks may request quartiles or the interquartile range.
summary = (
df.groupby(["n", "method"])
.agg(
median_seconds=("time_seconds", "median"),
min_seconds=("time_seconds", "min"),
max_seconds=("time_seconds", "max"),
trials=("time_seconds", "count"),
)
.reset_index()
)
summary.to_csv("hw_results_summary.csv", index=False)
summary
import matplotlib.pyplot as plt
for method_name, group in summary.groupby("method"):
plt.plot(
group["n"],
group["median_seconds"],
marker="o",
label=method_name,
)
plt.xlabel("input size n")
plt.ylabel("median running time, seconds")
plt.legend()
plt.tight_layout()
plt.savefig("hw_timing_plot.png", dpi=200)
plt.show()
What to include in the report
Report enough information to understand and reproduce the experiment:
- programming language, relevant library versions, and environment;
- input sizes and input-generation procedure;
- number of repetitions and random-seed policy;
- definition of the measured operation and timed region;
- a compact table or plot of the results;
- a concise interpretation, including surprising or noisy results.
Do not paste a large raw notebook output into the report. Select the tables, plots, and explanations that support your conclusions. Submit the raw measurements separately when requested.