Created
November 30, 2016 17:20
-
-
Save Highstaker/fc8792b8ffc73d0854f81816e74014c8 to your computer and use it in GitHub Desktop.
A function that takes a list and a number. Returns the maximum number that is no larger than def_max.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
A function that takes a list and a number. Returns the maximum number that is no larger than def_max. | |
""" | |
def bad_definedMax(in_array, def_max): | |
""" | |
O(N) (not counting the sorting) | |
""" | |
arr=in_array.copy() | |
arr.sort() | |
m = float("-inf") | |
for i in arr: | |
if i > m and i <= def_max: | |
m = i | |
return m if m != float("-inf") else None | |
def definedMax(in_array, def_max): | |
""" | |
O(logN) (not counting the sorting) | |
""" | |
arr=in_array.copy() | |
arr.sort() | |
while(len(arr)>1): | |
mid = len(arr)//2 | |
if arr[mid] == def_max: | |
return def_max | |
elif def_max < arr[mid]: | |
arr = arr[:mid] | |
elif def_max > arr[mid]: | |
arr = arr[mid:] | |
if arr[0] <= def_max: | |
return arr[0] | |
else: | |
return None | |
assert definedMax([1,2,3,4,6,8], 1) == 1 | |
assert definedMax([1,2,3,4,6,8], 2) == 2 | |
assert definedMax([1,2,3,4,6,8], 3) == 3 | |
assert definedMax([1,2,3,4,6,8], 4) == 4 | |
assert definedMax([1,2,3,4,6,8], 5) == 4 | |
assert definedMax([1,2,3,4,6,8], 6) == 6 | |
assert definedMax([1,2,3,4,6,8], 7) == 6 | |
assert definedMax([1,2,3,4,6,8], 8) == 8 | |
assert definedMax([1,2,3,4,6,8], 9) == 8 | |
from random import randint | |
for _ in range(100000): | |
VALUES = (0,100) | |
SIZE = (100,200) | |
arr = [randint(*VALUES) for i in range(randint(*SIZE))] | |
def_max = randint(*VALUES) | |
result = definedMax(arr, def_max) | |
bad_result = bad_definedMax(arr, def_max) | |
print(arr, def_max, result, bad_result, "="*30, sep="\n") | |
assert result == bad_result | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment