0

here's the code:

def findsort(something, alist):
    for item in alist:
        if item == something:
            return "found"
        else:
            return "not found"

def main():

    print(findsort(6, [3, 6, 1, 8, 11, 14]))

main()

for some reason, this doesn't work the way i thought it should work.

when i run this, it will say "not found." however, if i change the value i want to find to the first item in the list, the 3, it comes back as "found."

i have tried this with strings, and i get the same results.

can someone please tell me what i am doing wrong?

4

2 回答 2

5

因为如果在第一次迭代中项目不匹配,则进入 else 分支返回“未找到”,从而退出循环。

尝试这个:

def findsort(something, alist):
    for item in alist:
        if item == something:
            return "found"
    return "not found"

或者简单地说:

def findsort(something, alist):
    return "found" if something in alist else "not found"
于 2012-12-13T03:35:29.723 回答
2

@hyperboreus 指出了错误的原因(在else看到所有项目之前执行的分支)。

要在排序(“有序”)列表中查找项目,您可以使用执行二进制搜索()而不是线性搜索( )的bisect模块,例如,对于一百万个项目,二进制搜索将需要大约几十个操作,而对于线性搜索。O(log(n)item in alistO(n)

from bisect import bisect

findsort = lambda x, L: "found" if L and L[bisect(L,x) - 1] == x else "not found"
于 2012-12-13T04:17:25.427 回答