Specification for a function you don't need to write:
list_max(nums)
Returns the largest number in nums. You may assume nums has at least one element.
Your job: write a unittest.TestCase class, TestListMax, with test methods test_typical and test_single_element that verify this specification. Call list_max directly.
Checked against a correct implementation (all should pass) and a buggy one (at least one should fail).
import unittest
class TestListMax(unittest.TestCase):
def test_typical(self):
self.assertEqual(list_max([3, 7, 2]), 7)
def test_single_element(self):
self.assertEqual(list_max([5]), 5)
The choice of [3, 7, 2] for test_typical is deliberate, not arbitrary: the maximum (7) is in the middle of the list, not the first or last element. That specifically catches a broken implementation that only ever looks at nums[0] and ignores the rest — with an input like [7, 3, 2] (max already first), that exact same bug would go completely unnoticed, because the wrong logic happens to produce the right answer by coincidence.
test_single_element checks the boundary the specification explicitly allows: a list with just one element. It might feel like it "obviously" works if the general case does, but a real implementation using a loop like for x in nums[1:] needs the single-element case to still behave — here it does, since the loop body simply never executes and the initial value (nums[0]) is returned as-is.
Against the buggy implementation (return nums[0], ignoring everything else), test_single_element still passes — a one-element list's max genuinely is its first element, so the bug happens to be invisible there too. It's test_typical's carefully chosen middle-max input that actually catches it.
import unittest
class TestListMax(unittest.TestCase):
def test_typical(self):
self.assertEqual(list_max([3, 7, 2]), 7)
def test_single_element(self):
self.assertEqual(list_max([5]), 5)
Sign in to join the discussion.
No comments yet. Be the first to ask a question.
Press Run to execute your code, or Submit to test and complete this problem.