๐Ÿ’ป Exercise: Exercise: Cost per task

๐Ÿ“ Instructions

Write cost_per_task(traces) returning the mean of the 'cost_usd' field across all traces, as a float. Return 0.0 for an empty list. Standard library only.

๐Ÿงช Initial Code / Tests

๐Ÿ“„ evaluate.py
from unittest import TestCase
from exercise import cost_per_task


class Evaluate(TestCase):
    def test_averages_cost(self):
        self.assertAlmostEqual(cost_per_task([{'cost_usd': 0.02}, {'cost_usd': 0.04}]), 0.03)

    def test_empty_is_zero(self):
        self.assertEqual(cost_per_task([]), 0.0)

    def test_missing_cost_treated_as_zero(self):
        self.assertAlmostEqual(cost_per_task([{'cost_usd': 0.10}, {}]), 0.05)

โœ… Solutions

๐Ÿ“„ exercise.py
def cost_per_task(traces):
    if not traces:
        return 0.0
    return sum(float(t.get('cost_usd', 0.0)) for t in traces) / len(traces)