user4434316
user4434316

Reputation:

Python. How to optimize search functions

There any way to optimize these two functions ?

first function:

def searchList(list_, element):
    for i in range (0,len(list_)):
        if(list_[i] == element):
            return True      
    return False

second function:

return_list=[]
for x in list_search:
    if searchList(list_users,x)==False:
        return_list.append(x)

Upvotes: 2

Views: 410

Answers (4)

Ozgur Vatansever
Ozgur Vatansever

Reputation: 52163

Disclaimer: I assumed list_search has no duplicate elements. Otherwise, use this solution.

What you want is exactly the set complement of list_users in list_search.

As an alternative approach, you can use sets to get the difference between two lists and I think it should be much more performant than the naive look up which takes 0(n^2).

>>> list_search = [1, 2, 3, 4]
>>> list_users = [4, 5, 1, 6]
>>> print set(list_search).difference(list_users)
>>> {2, 3}

Upvotes: 2

ersteller
ersteller

Reputation: 71

What you are doing with your two functions is building the complement as ozgur pointed out. Using sets is the most easy thing here

>>> set([2,2,2,3,3,4])- set([1,2,2,4,5])
set([3])

your list_search would be the first list and your list_users the second list. The only difference is that your new user is only once in the result no matter how often it is in the list_search

Upvotes: 2

vaultah
vaultah

Reputation: 46533

Yes:

return_list = [x for x in list_search if x not in list_users]

The first function basically checks for membership, in which case you could use the in keyword. The second function can be reduced to a list comprehension to filter out elements from list_search list based on your condition.

Upvotes: 5

Bhargav Rao
Bhargav Rao

Reputation: 52101

For first function

def searchList(list, element):
   return element in list

You can make it in 1 line

searchList = lambda x,y: y in x

For 2nd, use a list comp like shown in the other answer

Upvotes: 4

Related Questions