daily log 01.05.21
HOW I BROKE IT DOWN:
import unittest
def get_median(arr):
if len(arr) == 2:
return ((arr[0] + arr[1])/2)
if len(arr)%2 == 0:
mid_upper = int(len(arr)/2)
mid_lower = mid_upper - 1
return ((arr[mid_lower] + arr[mid_upper])/2)
return arr[int(len(arr)/2)]
class Test(unittest.TestCase):
'''Test Cases'''
data = [
([1,2], 1.5),
([1,1], 1),
([0,0], 0),
([1,2,3], 2),
([1,2,3,4], 2.5)
]
def test_string_compression(self):
for [test_arr, expected] in self.data:
actual = get_median(test_arr)
self.assertEqual(actual, expected)
unittest.main(argv=[''], verbosity=2, exit=False)
def merge(arr1, arr2, merged_arr):
if len(arr1) == 0:
merged_arr += arr2
return merged_arr
if len(arr2) == 0:
merged_arr += arr1
return merged_arr
if arr1[0] < arr2[0]:
merged_arr.append(arr1.pop(0))
merge(arr1, arr2, merged_arr)
else:
merged_arr.append(arr2.pop(0))
merge(arr1, arr2, merged_arr)
return merged_arr
class Test(unittest.TestCase):
'''Test Cases'''
data = [
([1,2], [3,4], [1,2,3,4]),
([1,2,9,10], [3,4], [1,2,3,4,9,10])
]
def test_string_compression(self):
for [arr1, arr2, expected] in self.data:
actual = merge(arr1, arr2, [])
self.assertEqual(actual, expected)
unittest.main(argv=[''], verbosity=2, exit=False)
def find_median_sorted_arrays(arr1, arr2):
if len(arr1) == 0 and len(arr2) == 0:
return None
if len(arr1) == 0:
return get_median(arr2)
if len(arr2) == 0:
return get_median(arr1)
return get_median(merge(arr1, arr2, []))
class Test(unittest.TestCase):
'''Test Cases'''
data = [
([1,3], [2], 2),
([1,2], [3,4], 2.5),
([0,0], [0,0], 0),
([], [1], 1),
([2], [], 2)
]
def test_string_compression(self):
for [arr1, arr2, expected] in self.data:
actual = find_median_sorted_arrays(arr1, arr2)
self.assertEqual(actual, expected)
unittest.main(argv=[''], verbosity=2, exit=False)
SUBMISSION
(Next challenge is to do better with space and time!!)
class Solution:
def get_median(self, arr):
if len(arr) == 2:
return ((arr[0] + arr[1])/2)
if len(arr)%2 == 0:
mid_upper = int(len(arr)/2)
mid_lower = mid_upper - 1
return ((arr[mid_lower] + arr[mid_upper])/2)
return arr[int(len(arr)/2)]
def merge(self, arr1, arr2, merged_arr):
if len(arr1) == 0:
merged_arr += arr2
return merged_arr
if len(arr2) == 0:
merged_arr += arr1
return merged_arr
if arr1[0] < arr2[0]:
merged_arr.append(arr1.pop(0))
self.merge(arr1, arr2, merged_arr)
else:
merged_arr.append(arr2.pop(0))
self.merge(arr1, arr2, merged_arr)
return merged_arr
def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
arr1 = nums1
arr2 = nums2
if len(arr1) == 0 and len(arr2) == 0:
return None
if len(arr1) == 0:
return self.get_median(arr2)
if len(arr2) == 0:
return self.get_median(arr1)
return self.get_median(self.merge(arr1, arr2, []))