Рубрики
Без рубрики

Лучший линейный поиск

# Better_linear_search.py # Эта программа использует линейный поиск массива размера n для # значение … Помечено Python, программирование, алгоритмы.

# better_linear_search.py
#   This program uses a linear search of an array of size n for
#   value x but unlike its predecessor linear_search.py it does
#   not traverse the entire array regardless of value x being
#   discovered.  It simply returns the value immediately once
#   the value of x in found in the array.  If not found then it 
#   will just return text saying it wasnt found.
# by: Scott Gordon

things = ["bike", "house", "cat", "computer", "hammer"]

def linear_search(array, n, x):
    for i in range(1, n):
        if array[i] == x:
            return i
    return "Not found!" 

print(linear_search(things, 5, "cat")) # prints the index of "cat" which is 2
print(linear_search(things, 5, "hammer")) # prints the index of "hammer" which is 4
print(linear_search(things, 5, "pasta")) # prints Not found!

Оригинал: “https://dev.to/sagordondev/better-linear-search-44p1”