Skip to content Skip to sidebar Skip to footer

Python3 - Learning About Searching, This Very Simple Example Does Not Work Right

here's the code: def findsort(something, alist): for item in alist: if item == something: return 'found' else: return 'not found' def m

Solution 1:

Because if in the first iteration the item doesn't match, you go into the else branch returning "not found", thus exiting the loop.

Try this:

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

or simply:

deffindsort(something, alist):
    return"found"if something in alist else"not found"

Solution 2:

@hyperboreus pointed out the cause of the error (the else branch executing before all items are seen).

To find an item in a sorted ("ordered") list you could use bisect module that performs binary search (O(log(n)) instead of linear search item in alist (O(n)) e.g., for a million items binary search would require around a couple dozen operations against a million operations for the linear search.

from bisect import bisect

findsort = lambda x, L: "found"if L and L[bisect(L,x) - 1] == x else"not found"

Post a Comment for "Python3 - Learning About Searching, This Very Simple Example Does Not Work Right"