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.