๐Ÿ’ป Exercise: Exercise: Enforce cost and step caps

๐Ÿ“ Instructions

Write enforce_caps(steps, cost, max_steps=None, max_cost=None) returning a halt-reason string if a cap is exceeded, else None. Check steps first: if max_steps is set and steps >= max_steps, return a message containing 'max_steps'; then if max_cost is set and cost >= max_cost, return a message containing 'max_cost'. An unset cap (None) is never enforced. Standard library only.

๐Ÿงช Initial Code / Tests

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


class Evaluate(TestCase):
    def test_step_cap_fires(self):
        self.assertIn('max_steps', enforce_caps(5, 0.0, max_steps=5))

    def test_cost_cap_fires(self):
        self.assertIn('max_cost', enforce_caps(1, 0.51, max_cost=0.50))

    def test_within_caps_returns_none(self):
        self.assertIsNone(enforce_caps(4, 0.10, max_steps=5, max_cost=0.50))

    def test_no_caps_set_never_halts(self):
        self.assertIsNone(enforce_caps(999, 999.0))

โœ… Solutions

๐Ÿ“„ exercise.py
def enforce_caps(steps, cost, max_steps=None, max_cost=None):
    if max_steps is not None and steps >= max_steps:
        return 'max_steps (' + str(max_steps) + ') reached'
    if max_cost is not None and cost >= max_cost:
        return 'max_cost ($' + str(max_cost) + ') reached'
    return None