Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Linear Search บน List และ Tuple ใน Python

Linear Search ค้นหาตั้งแต่ต้นจนจบ หยุดเมื่อเจอ

การทำงาน

  1. เตรียมข้อมูลและค่าที่ต้องการค้น
  2. วนลูปตรวจสอบแต่ละสมาชิก
  3. เจอแล้วคืนผล หากจบลูปไม่เจอคืน "not found"

ตัวอย่างโค้ด

def linear_search(iterable, element):
    for i in range(len(iterable)):
        if iterable[i] == element:
            return f"{element} 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))

ผลลัพธ์

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

สรุป

ทำงานได้กับ List และ Tuple ใดๆ สำหรับข้อมูลเล็ก ใช้ได้ดี สำหรับข้อมูลใหญ่ควรใช้ Binary Search (ต้องเรียงก่อน)