2

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)
3
  • 1
    Before asking for a faster way to do something, you should first explain what you are trying to do! Commented Feb 17, 2015 at 19:39
  • Convert list_users to a set and check for item simply using the in operator. Commented Feb 17, 2015 at 19:40
  • 5
    Optimize for what? Readability? Speed? Memory usage? Either way, since your question is about working code, it's better suited for codereview.stackexchange.com Commented Feb 17, 2015 at 19:40

4 Answers 4

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

in is O(n) for list. If you wanted to get really crazy you can write a binary search (if applicable) which would reduce this to logn!
4

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

1 Comment

Good point ! first time i seen this question and vote the first answer! but i miss this elegant answer!
2

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

Comments

2

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}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.