Solutions
Use these to check your work after you’ve tried the exercises. If something differs, treat it as a debugging opportunity.
Exercise 1
int sum_vec(const std::vector<int>& v) {
return std::accumulate(v.begin(), v.end(), 0);
}
Bind with:
m.def("sum_vec", &sum_vec);
Exercise 2
std::vector<double> normalize(const std::vector<double>& v) {
if (v.empty()) throw std::runtime_error("normalize: empty input");
double max_abs = 0.0;
for (double x : v) max_abs = std::max(max_abs, std::abs(x));
if (max_abs == 0.0) return v;
std::vector<double> out = v;
for (double &x : out) x /= max_abs;
return out;
}