From 74233022a0608b0ee25d3514a87a36e40bc821ac Mon Sep 17 00:00:00 2001 From: anneCoder1805 <66819522+anneCoder1805@users.noreply.github.com> Date: Tue, 20 Oct 2020 16:08:49 +0530 Subject: [PATCH] Median of Two Arrays (#3554) * Create medianOf TwoArrays.py This code finds the median of two arrays (which may or may not be sorted initially). Example: Enter elements of an array: 1 5 4 2 Enter elements of another array: 1 7 4 2 7 The median of two arrays is : 4 * Rename medianOf TwoArrays.py to median_of _two_arrays.py * Rename median_of _two_arrays.py to median_of_two_arrays.py * Update median_of_two_arrays.py * Update median_of_two_arrays.py * Update median_of_two_arrays.py * Update median_of_two_arrays.py * Update median_of_two_arrays.py * Update median_of_two_arrays.py * Update median_of_two_arrays.py * Update median_of_two_arrays.py * Update median_of_two_arrays.py * Update median_of_two_arrays.py * Update median_of_two_arrays.py * Update median_of_two_arrays.py * Update median_of_two_arrays.py * Update median_of_two_arrays.py * Update median_of_two_arrays.py * Update median_of_two_arrays.py * Update median_of_two_arrays.py --- other/median_of_two_arrays.py | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 other/median_of_two_arrays.py diff --git a/other/median_of_two_arrays.py b/other/median_of_two_arrays.py new file mode 100644 index 0000000..cde12f5 --- /dev/null +++ b/other/median_of_two_arrays.py @@ -0,0 +1,33 @@ +from typing import List + + +def median_of_two_arrays(nums1: List[float], nums2: List[float]) -> float: + """ + >>> median_of_two_arrays([1, 2], [3]) + 2 + >>> median_of_two_arrays([0, -1.1], [2.5, 1]) + 0.5 + >>> median_of_two_arrays([], [2.5, 1]) + 1.75 + >>> median_of_two_arrays([], [0]) + 0 + >>> median_of_two_arrays([], []) + Traceback (most recent call last): + ... + IndexError: list index out of range + """ + all_numbers = sorted(nums1 + nums2) + div, mod = divmod(len(all_numbers), 2) + if mod == 1: + return all_numbers[div] + else: + return (all_numbers[div] + all_numbers[div - 1]) / 2 + + +if __name__ == "__main__": + import doctest + + doctest.testmod() + array_1 = [float(x) for x in input("Enter the elements of first array: ").split()] + array_2 = [float(x) for x in input("Enter the elements of second array: ").split()] + print(f"The median of two arrays is: {median_of_two_arrays(array_1, array_2)}") -- GitLab