python顺序搜索的两种形式

python顺序搜索的两种形式

分类

1、无序列表顺序搜索,从列表中的第一个元素开始,按默认顺序逐个查看。

直到找到目标元素或查看列表。如果查看列表后仍未找到目标元素,则目标元素不在列表中。

2、有序列表顺序搜索,假设列表中的元素按顺序排列。

如果有目标元素,出现在n个位置的任何位置的可能性还是一样的,所以比较次数和无序列表一样。如果没有目标元素,搜索效率会提高。

实例

defUnsequentialSearch(ulist,item):
"""
这个函数接受列表与目标元素作为参数,并返回一个表示目标元素是否存在的布尔值。布尔型变量found的初始值为False,如果找到目标元素,就将它的值改为Tru
"""
pos=0
found=False
whilepos<len(ulist)andnotfound:
ifulist[pos]==item:
found=True
else:
pos+=1
returnfound

defOrderedListSequentialSearch(ulist,item):
pos=0
found=False
stop=False
whilepos<len(ulist)andnotfoundandnotstop:
ifulist[pos]==item:
found=True
else:
ifulist[pos]>item:
stop=True
else:
pos=pos+1
returnfound

if__name__=='__main__':
#ret=UnsequentialSearch([1,3,10,5,8],7)
#print(ret)
ret=OrderedListSequentialSearch([1,3,5,7,10],6)
print(ret)

以上就是python顺序搜索的两种形式,希望对大家有所帮助。更多python学习指路:python基础教程