/search.py Secret
Last active
February 11, 2025 13:09
-
Star
(0)
You must be signed in to star a gist -
Fork
(290)
You must be signed in to fork a gist
-
-
Save dvmn-tasks/2bc5a09d67723164fc4f5f778e69858b to your computer and use it in GitHub Desktop.
Упражнение на чтение кода №1 "Разбираемся в чужом алгоритме".
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
from random import sample | |
def s(list_, target): | |
left, right = 0, len(list_) - 1 | |
while left <= right: | |
middle = (left + right) // 2 | |
if list_[middle] < target: | |
left = middle + 1 | |
elif list_[middle] > target: | |
right = middle - 1 | |
else: | |
return middle | |
return | |
if __name__ == "__main__": | |
list_len = 10 | |
rand_list = sorted(sample(range(0, 101, 2), list_len)) | |
try: | |
target = int(input('Pick a number between 0-100: ')) | |
target_index = s(rand_list, target) | |
print(f'List: {rand_list}') | |
if target_index is not None: | |
print(f'Found {target} in index {target_index}') | |
else: | |
print(f'Cannot find {target} in the list') | |
except ValueError: | |
print('Invalid input') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment