How to improve this code?

André andre.roberge at gmail.com
Mon Sep 14 21:33:17 EDT 2009


On Sep 14, 10:16 pm, "Diez B. Roggisch" <de... at nospam.web.de> wrote:
> Oltmans schrieb:
>
>
>
> > Hello,
>
> > Is there someway I can improve the following code(pythonically)?
> > (Copying from IDLE)
> > match=[1,2,3,4,5]
>
> > def elementsPresent(aList):
> >    result=False
> >    if not aList:
> >            return False
> >    for e in aList:
> >            if e in match:
> >                    result=True
> >            else:
> >                    result = False
> >    return result
> >  elementsPresent([6,7,8,9,5]) # should return True because 5 is
> > present in list named match.
>
> > Is there somehow I can improve code in elementsPresent()? I'm not a
> > very good programmer but I sense that idea of using a variable named
> > 'result' inside elementsPresent() doesn't sound very good. Any ideas
> > will be highly appreciated.
>
> 1) don't use a global variable for your function. Pass both parameters
> 2) make the lookup O(1) instead O(n) for you match by using a set
> 3) stop when something is found
> 4) Unless you want the code to be working with things that are not a
> list, but False, the first "if" is superflous
>
> def elementsPresent(aList, match):
>      match = set(match)
>      for item in aList:
>          if item in match:
>              return True
>      return False
>
> It might actually be that turning both lists to sets & checking if these
> overlap is faster because it's in pure C.
>
> Diez

Here's an example using sets:

>>> def is_present(list_1, list_2):
...    if set(list_1).intersection(set(list_2)):
...       return True
...    return False
...
>>> is_present([1,2,3], [4,5,6])
False
>>> is_present([1,2,3], [0,2,4])
True


André



More information about the Python-list mailing list