Need help porting Perl function

Sam Denton stdenton at sbcglobal.net
Sat Jun 7 17:11:29 EDT 2008


kj wrote:
> Hi.  I'd like to port a Perl function that does something I don't
> know how to do in Python.  (In fact, it may even be something that
> is distinctly un-Pythonic!)
> 
> The original Perl function takes a reference to an array, removes
> from this array all the elements that satisfy a particular criterion,
> and returns the list consisting of the removed elements.  Hence
> this function returns a value *and* has a major side effect, namely
> the target array of the original argument will be modified (this
> is the part I suspect may be un-Pythonic).

The two solutions thus far use the .index() method, which itself runs in 
O(n) time.  This means that the provided functions run in O(n^2) time, 
which can be a problem if the list is big.  I'd go with this:

def partition(alist, criteria):
     list1, list2 = [], []
     for item in alist:
         if criteria(item):
             list1.append(item)
         else:
             list2.append(item)
     return (list1, list2)

def mod(alist, criteria=lambda x: x % 2 == 0):
     alist[:], blist = partition(alist, criteria)
     return blist


 >>> partition(range(10), lambda x: x % 2 == 0)
([0, 2, 4, 6, 8], [1, 3, 5, 7, 9])
 >>> l=range(10)
 >>> mod(l)
[1, 3, 5, 7, 9]
 >>> l
[0, 2, 4, 6, 8]



More information about the Python-list mailing list