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