Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Tìm kiếm tuyến tính trên list hoặc tuple trong Python


Tìm kiếm tuyến tính: duyệt từ đầu đến cuối, dừng khi tìm thấy.

Triển khai

def linear_search(iterable, element):
    is_found = False
    for i in range(len(iterable)):
        if iterable[i] == element:
            is_found = True
            return f"{element} found"
    if not is_found:
        return f"{element} not found"

numbers_list = [1, 2, 3, 4, 5, 6]
numbers_tuple = (1, 2, 3, 4, 5, 6)
print("List:", linear_search(numbers_list, 3))
print("List:", linear_search(numbers_list, 7))
print("Tuple:", linear_search(numbers_tuple, 3))
print("Tuple:", linear_search(numbers_tuple, 7))

Đầu ra

List: 3 found
List: 7 not found
Tuple: 3 found
Tuple: 7 not found

Kết luận

Thuật toán đơn giản, phù hợp dữ liệu nhỏ hoặc không sắp xếp.