Computer Exercise 4: Worked solutions
Algorithms, Programming, and Data Representation · Module 92313 · Exercise 4
Parsing sensor logs, detecting instant and sustained alerts, daily classification, interpolation, and weekly reporting. Try each task before opening its worked steps. Personalized inputs and results are omitted; apply the methods to your own assigned data.
Task 1: Parse wearable log rows
Connected topic: Related APDR guide section
Task 01 · Parse wearable log rows
Try first: Parse three comma-separated fields, preserving valid rows with missing sensor values.
Attempted it? Open the worked steps
Task 01 · worked solution
Split each line on commas and trim whitespace. Accept exactly three fields and require a timestamp.
Map blank, NA, None, and NaN readings to None. Convert other readings to float; if conversion fails, skip the malformed row.
Do not discard a row merely because one sensor reading is missing. Test blank fields, malformed numeric text, and wrong field counts.
Reference implementation:
def parse_log(raw_lines): rows = [] for line in raw_lines: fields = [part.strip() for part in line.split(",")] if len(fields) != 3 or not fields[0]: continue try: values = [] for field in fields[1:]: if not field or field.lower() in ("nan", "na", "none"): values.append(None) else: value = float(field) values.append(None if value != value else value) rows.append((fields[0], *values)) except (TypeError, ValueError): continue return rows
Task 2: Flag instantaneous heart-rate anomalies
Connected topic: Related APDR guide section
Task 02 · Flag instantaneous heart-rate anomalies
Try first: Return indices where a present heart-rate reading reaches 180 bpm.
Attempted it? Open the worked steps
Task 02 · worked solution
Enumerate the ordered log so results refer to the original row positions.
A reading qualifies when it is not None and is at least 180. A missing reading is not an anomaly.
Check values 179, 180, and None to confirm the inclusive boundary.
Reference implementation:
def flag_instant_anomalies(log): return [i for i, row in enumerate(log) if row[1] is not None and row[1] >= 180]
Task 3: Find sustained high-heart-rate intervals
Connected topic: Related APDR guide section
Task 03 · Find sustained high-heart-rate intervals
Try first: Scan once, recording the start and end of each uninterrupted qualifying interval.
Attempted it? Open the worked steps
Task 03 · worked solution
Start a run when heart rate first reaches the threshold. A below-threshold or missing row closes it; never join across a gap.
With parseable timestamps, duration is elapsed time from the first qualifying reading to the last. For ordinal timestamps only, the fallback counts one minute per row; this assumes one-minute sampling. For example, timestamps 00:00, 00:01, and 00:02 span two elapsed minutes, while three ordinal samples count as three minutes under that fallback.
Return inclusive (start, end) pairs only when duration meets the requested minimum. Also close a run that reaches the final row.
Reference implementation:
from datetime import datetime def flag_sustained_anomalies(log, threshold, min_duration_min): if len(log) < 2: return [] def keep_if_long(result, start, end): try: a = datetime.fromisoformat(str(log[start][0])) b = datetime.fromisoformat(str(log[end][0])) duration = (b - a).total_seconds() / 60 except (TypeError, ValueError): duration = end - start + 1 # assumes one-minute sample spacing if duration >= min_duration_min: result.append((start, end)) result, start = [], None for i, row in enumerate(log): if row[1] is not None and row[1] >= threshold: if start is None: start = i elif start is not None: keep_if_long(result, start, i - 1) start = None if start is not None: keep_if_long(result, start, len(log) - 1) return result
Task 4: Classify a day with ordered rules
Connected topic: Related APDR guide section
Task 04 · Classify a day with ordered rules
Try first: Apply the overtraining rules first, then distinguish active from rest days.
Attempted it? Open the worked steps
Task 04 · worked solution
Collect valid heart-rate readings and sum steps, treating missing steps as zero.
Return overtrained if there are at least three instantaneous anomalies or the valid-reading mean is at least 130. This precedence must come before active/rest.
Otherwise, no valid heart-rate readings means rest. With readings, at least 5000 steps means active; otherwise rest.
Reference implementation:
def classify_day(log): hrs = [row[1] for row in log if row[1] is not None] steps = sum(row[2] or 0 for row in log) if len(flag_instant_anomalies(log)) >= 3 or (hrs and sum(hrs)/len(hrs) >= 130): return "overtrained" if not hrs: return "rest" if steps >= 5000: return "active" return "rest"
Task 5: Interpolate short missing runs
Connected topic: Related APDR guide section
Task 05 · Interpolate short missing runs
Try first: Fill only interior runs of at most three missing heart rates when both endpoints exist.
Attempted it? Open the worked steps
Task 05 · worked solution
Find each consecutive missing run and count its length. Leave leading, trailing, and runs longer than three unchanged.
For m missing values between left and right, fill offset j (1 through m) with left + (right − left) × jm + 1.
Preserve timestamps and step counts. Return new tuples so the input rows are not mutated.
Reference implementation:
def interpolate_missing(log): out = [list(row) for row in log] i = 0 while i < len(out): if out[i][1] is not None: i += 1; continue start = i while i < len(out) and out[i][1] is None: i += 1 count = i - start if (count <= 3 and start > 0 and i < len(out) and out[start-1][1] is not None and out[i][1] is not None): left, right = out[start-1][1], out[i][1] for j in range(count): out[start+j][1] = left + (right-left)*(j+1)/(count+1) return [tuple(row) for row in out]
Task 6: Summarize a week
Connected topic: Related APDR guide section
Task 06 · Summarize a week
Try first: Compute daily values and weekly totals in one pass over the day logs.
Attempted it? Open the worked steps
Task 06 · worked solution
For each day, calculate that day’s steps, classification, and number of readings. Store the daily steps value in that day’s record.
Separately accumulate weekly steps and increment exactly one classification count per day. Do not put the running weekly total into each daily record.
Check that daily steps sum to the weekly total and the three class counts sum to the number of days. The supplied student.py stores cumulative steps in the daily field; this solution corrects it.
Reference implementation:
def weekly_summary(week_logs): days, total = [], 0 counts = {"rest": 0, "active": 0, "overtrained": 0} for log in week_logs: steps = sum(row[2] or 0 for row in log) label = classify_day(log) total += steps counts[label] += 1 days.append({"total_steps": steps, "classification": label, "readings": len(log)}) return {"days": days, "total_steps": total, "rest_days": counts["rest"], "active_days": counts["active"], "overtrained_days": counts["overtrained"]}
Task 7: Detect a recovery trend
Connected topic: Related APDR guide section
Task 07 · Detect a recovery trend
Try first: Compare daily mean heart rates in chronological order, ignoring days with no valid readings.
Attempted it? Open the worked steps
Task 07 · worked solution
Compute one mean per day with at least one valid heart-rate value. Skip empty days rather than treating their mean as zero.
Require at least three means. A strict recovery trend holds only if every successive mean is lower than the previous one.
Test a descending sequence, a tie, an increase, and fewer than three valid days.
Reference implementation:
def detect_recovery_trend(week_logs): means = [] for log in week_logs: values = [row[1] for row in log if row[1] is not None] if values: means.append(sum(values) / len(values)) return len(means) >= 3 and all(a > b for a, b in zip(means, means[1:]))
Task 8: Handle boundaries and missing samples
Connected topic: Related APDR guide section
Task 08 · Handle boundaries and missing samples
Try first: Check empty, single-row, final-run, and missing-reading cases for sustained detection.
Attempted it? Open the worked steps
Task 08 · worked solution
An empty or one-row log cannot establish a sustained interval under the supplied implementation, so return an empty list.
A qualifying run ending at the final sample still needs to be evaluated; close it after the loop.
Missing heart rate closes a run. Do not bridge the missing sample, even if the readings on both sides qualify.
Task 9: Keep anomaly detection linear
Connected topic: Related APDR guide section
Task 09 · Keep anomaly detection linear
Try first: Explain why a single ordered pass is O(n), and avoid rescanning all prefixes.
Attempted it? Open the worked steps
Task 09 · worked solution
Each row is visited once. The active run is represented by one start index, so each transition takes constant work.
The scan therefore takes O(n) time and O(k) output space, where k is the number of detected intervals.
Repeatedly slicing or recounting the prefix inside the loop can make an otherwise simple solution quadratic.
Task 10: Integrate the alert report
Connected topic: Related APDR guide section
Task 10 · Integrate the alert report
Try first: Compose the daily detectors, classification, weekly summary, and recovery trend into one result.
Attempted it? Open the worked steps
Task 10 · worked solution
For each daily log, store instant anomaly indices, sustained intervals using the specified threshold and duration, and its classification.
Add weekly_summary and detect_recovery_trend results under stable top-level keys. Keep tuple intervals; the JSON encoder serializes tuples as arrays.
Check an empty week and a small synthetic week. Ensure each daily alert aligns with its input day.
Reference implementation:
def generate_alert_report(week_logs): alerts = [] for log in week_logs: alerts.append({"instant_anomalies": flag_instant_anomalies(log), "sustained_anomalies": flag_sustained_anomalies(log, 160, 3), "classification": classify_day(log)}) return {"daily_alerts": alerts, "summary": weekly_summary(week_logs), "recovery_trend": detect_recovery_trend(week_logs)}
Personal worked solutions based on the APDR Computer Exercise 4 sheet, explained in my own words. Examples are generic; use your own assigned inputs for any personalized result. Not an official FAU publication; check course details against current materials. Made by Thanate Amornjiraporn (Focus).