Created
August 27, 2022 04:08
-
-
Save ssbozy/c153f14873ad9ff47ed08800073dc3e8 to your computer and use it in GitHub Desktop.
Basic binary search with logger
This file contains 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
import logging | |
from typing import Optional | |
def create_logger(logger_type=logging.DEBUG): | |
logger = logging.getLogger(__name__) | |
logger.setLevel(logger_type) | |
stream_handler = logging.StreamHandler() | |
formatter = logging.Formatter('%(asctime)s : %(levelname)s : %(funcName)s : %(message)s') | |
stream_handler.setFormatter(formatter) | |
logger.addHandler(stream_handler) | |
return logger | |
logger = create_logger() | |
def binary_search(sorted_list:list, target:int) -> Optional[int]: | |
''' | |
inputs: a sorted list of integers and a target integer | |
returns the target integer if found or -1 | |
''' | |
if sorted_list and sorted_list[0] <= target <= sorted_list[-1]: | |
ptr = len(sorted_list) // 2 #integer division. | |
logger.debug(f"{sorted_list}, ptr: {ptr}, comparing {target} and {sorted_list[ptr]}") | |
if sorted_list[ptr] > target: | |
logger.debug(f"searching {target} in {sorted_list[:ptr]}") | |
return binary_search(sorted_list[:ptr], target) | |
if sorted_list[ptr] < target: | |
logger.debug(f"searching {target} in {sorted_list[ptr:]}") | |
return binary_search(sorted_list[ptr:], target) | |
else: | |
logger.debug(f"found {target}") | |
return target | |
else: | |
return None | |
def main() -> None: | |
logger.info(binary_search(range(20), 3)) | |
print(type(logger)) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment