Python中列表或元組的線性搜尋


在本文中,我們將學習如何對列表和元組應用線性搜尋。

線性搜尋從第一個元素開始搜尋,一直到列表或元組的末尾。一旦找到所需的元素,它就會停止檢查。

線性搜尋 - 列表和元組

按照以下步驟對列表和元組實施線性搜尋。

  • 初始化列表或元組和一個元素。
  • 遍歷列表或元組並檢查元素。
  • 每當找到元素時就中斷迴圈並標記一個標誌。
  • 根據標誌列印未找到元素訊息。

示例

讓我們看下程式碼。

# function for linear search
def linear_search(iterable, element):
   # flag for marking
   is_found = False
   # iterating over the iterable
   for i in range(len(iterable)):
      # checking the element
      if iterable[i] == element:
         # marking the flag and returning respective message
         is_found = True
         return f"{element} found"

   # checking the existence of element
   if not is_found:
      # returning not found message
      return f"{element} not found"

# initializing the list
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

結論

如果你對此文章有任何疑問,請在評論區提及。

更新於:2020年11月13日

3K+ 瀏覽量

啟動您的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.