diff --git a/src/algorithms/__init__.py b/src/algorithms/__init__.py new file mode 100644 index 0000000..92f33b3 --- /dev/null +++ b/src/algorithms/__init__.py @@ -0,0 +1 @@ +# algorithms package diff --git a/src/algorithms/find_max.py b/src/algorithms/find_max.py new file mode 100644 index 0000000..e71fd53 --- /dev/null +++ b/src/algorithms/find_max.py @@ -0,0 +1,14 @@ +"""find_max — 从数字列表中查找最大值""" + +from __future__ import annotations + + +def find_max(nums: list[int | float]) -> int | float | None: + """返回列表中的最大值,空列表返回 None。""" + if not nums: + return None + result = nums[0] + for num in nums[1:]: + if num > result: + result = num + return result diff --git a/tests/test_find_max.py b/tests/test_find_max.py new file mode 100644 index 0000000..1bbdb1b --- /dev/null +++ b/tests/test_find_max.py @@ -0,0 +1,28 @@ +"""find_max 单元测试""" + +import pytest + +from src.algorithms.find_max import find_max + + +class TestFindMax: + def test_normal_list(self): + assert find_max([3, 1, 4, 1, 5, 9, 2, 6]) == 9 + + def test_empty_list(self): + assert find_max([]) is None + + def test_single_element(self): + assert find_max([42]) == 42 + + def test_negative_numbers(self): + assert find_max([-5, -1, -10, -3]) == -1 + + def test_floats(self): + assert find_max([1.5, 2.7, 0.3, 3.14]) == 3.14 + + def test_mixed_int_float(self): + assert find_max([1, 2.5, 3, 0.1]) == 3 + + def test_duplicate_max(self): + assert find_max([7, 7, 7]) == 7