Skip to content

Commit e25d0e9

Browse files
committed
add a new algo in the number_theory
1 parent 241f6ea commit e25d0e9

1 file changed

Lines changed: 59 additions & 0 deletions

File tree

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
"""
2+
https://www.enjoyalgorithms.com/blog/median-of-two-sorted-arrays
3+
"""
4+
5+
def find_median_sorted_arrays(nums1: list[int], nums2: list[int]) -> float:
6+
"""
7+
Find the median of two arrays.
8+
9+
Args:
10+
nums1: The first array.
11+
nums2: The second array.
12+
13+
Returns:
14+
The median of the two arrays.
15+
16+
Examples:
17+
>>> find_median_sorted_arrays([1, 3], [2])
18+
2.0
19+
20+
>>> find_median_sorted_arrays([1, 2], [3, 4])
21+
2.5
22+
23+
>>> find_median_sorted_arrays([0, 0], [0, 0])
24+
0.0
25+
26+
>>> find_median_sorted_arrays([], [])
27+
Traceback (most recent call last):
28+
...
29+
ValueError: Both input arrays are empty.
30+
31+
>>> find_median_sorted_arrays([], [1])
32+
1.0
33+
34+
>>> find_median_sorted_arrays([-1000], [1000])
35+
0.0
36+
37+
>>> find_median_sorted_arrays([-1.1, -2.2], [-3.3, -4.4])
38+
-2.75
39+
"""
40+
if not nums1 and not nums2:
41+
raise ValueError("Both input arrays are empty.")
42+
43+
# Merge the arrays into a single sorted array.
44+
merged = sorted(nums1 + nums2)
45+
total = len(merged)
46+
47+
if total % 2 == 1: # If the total number of elements is odd
48+
return float(merged[total // 2]) # then return the middle element
49+
50+
# If the total number of elements is even, calculate
51+
# the average of the two middle elements as the median.
52+
middle1 = merged[total // 2 - 1]
53+
middle2 = merged[total // 2]
54+
return (float(middle1) + float(middle2)) / 2.0
55+
56+
57+
if __name__ == "__main__":
58+
import doctest
59+
doctest.testmod()

0 commit comments

Comments
 (0)