微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

将参数传递给python上的线性搜索函数

如何解决将参数传递给python上的线性搜索函数

我有一个线性搜索,其中有一个单词列表和一个单词。搜索检查单词是否在列表中。我继续尝试传递我的参数来测试该函数,但是当我运行该程序时,什么也没有出现。如果你能看看这段代码并告诉我我哪里出错了,那就太好了。

def isin(alist,word):
    found = False
    length = len(alist)
    pos = 0
    while found == False and pos < length:
        if alist[pos] == word:
            found == True
        else:
            pos = pos + 1
    return found


words = ["child","adult","cat","dog","whale"]

if isin(words,"dog"):
    print("yes")
else:
    print("no")

解决方法

您的第 found == True 行有问题。应该是 found = True

def isin(alist,word):
    found = False
    length = len(alist)
    pos = 0
    while found == False and pos < length:
        if alist[pos] == word:
            found = True
        else:
            pos = pos + 1
    return found

您可以简化在一行中完成相同任务的方法:

def isin(alist,word):
    return True if word in alist else False
,

你做了很多额外的工作。这样做:

def isin(alist,word):
    if word in alist:
        return True
    else:
        return False

words = ["child","adult","cat","dog","whale"]

if isin(words,"dog"):
    print("yes")
else:
    print("no")

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。