python顺序搜索的两种形式

404次阅读
没有评论

python顺序搜索的两种形式

python顺序搜索分类

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

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

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

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

python顺序搜索实例

def UnsequentialSearch(ulist, item):
    """
    这个函数接受列表与目标元素作为参数, 并返回一个表示目标元素是否存在的布尔值。布尔型变量found的初始值为False, 如果找到目标元素,就将它的值改为Tru
    """
    pos = 0
    found = False
    while pos < len(ulist) and not found:
        if ulist[pos] == item:
            found = True
        else:
            pos += 1
    return found
 
def OrderedListSequentialSearch(ulist,item):
    pos = 0
    found = False
    stop = False
    while pos < len(ulist) and not found and not stop:
        if ulist[pos] == item:
            found = True
        else:
            if ulist[pos] > item:
                stop = True
            else:
                pos = pos+1
    return found
 
if __name__ == '__main__':
    # ret = UnsequentialSearch([1, 3, 10, 5, 8], 7)
    # print(ret)
    ret = OrderedListSequentialSearch([1, 3, 5, 7, 10], 6)
    print(ret)
神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试

相关文章:

版权声明:wuyou2022-04-04发表,共计987字。
新手QQ群:570568346,欢迎进群讨论 Python51学习