Skip to content

Commit 66f8c22

Browse files
authored
Add array traversal logic building problem
This module includes functions for finding the maximum, minimum, and sum of elements in an array, with appropriate error handling and examples.
1 parent 49c9975 commit 66f8c22

File tree

1 file changed

+96
-0
lines changed

1 file changed

+96
-0
lines changed
Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
"""Array Traversal.
2+
3+
This module contains functions for common array traversal operations,
4+
including finding maximum, minimum, and sum of elements.
5+
"""
6+
7+
8+
def find_max(arr: list[int | float]) -> int | float:
9+
"""
10+
Find the maximum element in an array.
11+
12+
Args:
13+
arr: List of numbers
14+
15+
Returns:
16+
The maximum value in the array
17+
18+
Raises:
19+
ValueError: If the array is empty
20+
21+
Examples:
22+
>>> find_max([1, 5, 3, 9, 2])
23+
9
24+
>>> find_max([-1, -5, -3])
25+
-1
26+
>>> find_max([42])
27+
42
28+
>>> find_max([1.5, 2.7, 1.2])
29+
2.7
30+
>>> find_max([])
31+
Traceback (most recent call last):
32+
...
33+
ValueError: Array cannot be empty
34+
"""
35+
if not arr:
36+
raise ValueError("Array cannot be empty")
37+
return max(arr)
38+
39+
40+
def find_min(arr: list[int | float]) -> int | float:
41+
"""
42+
Find the minimum element in an array.
43+
44+
Args:
45+
arr: List of numbers
46+
47+
Returns:
48+
The minimum value in the array
49+
50+
Raises:
51+
ValueError: If the array is empty
52+
53+
Examples:
54+
>>> find_min([1, 5, 3, 9, 2])
55+
1
56+
>>> find_min([-1, -5, -3])
57+
-5
58+
>>> find_min([42])
59+
42
60+
>>> find_min([])
61+
Traceback (most recent call last):
62+
...
63+
ValueError: Array cannot be empty
64+
"""
65+
if not arr:
66+
raise ValueError("Array cannot be empty")
67+
return min(arr)
68+
69+
70+
def array_sum(arr: list[int | float]) -> int | float:
71+
"""
72+
Calculate the sum of all elements in an array.
73+
74+
Args:
75+
arr: List of numbers
76+
77+
Returns:
78+
The sum of all values in the array
79+
80+
Examples:
81+
>>> array_sum([1, 2, 3, 4, 5])
82+
15
83+
>>> array_sum([-1, 1, -2, 2])
84+
0
85+
>>> array_sum([1.5, 2.5, 3.0])
86+
7.0
87+
>>> array_sum([])
88+
0
89+
"""
90+
return sum(arr)
91+
92+
93+
if __name__ == "__main__":
94+
import doctest
95+
96+
doctest.testmod()

0 commit comments

Comments
 (0)