Ask Your Question

Partition list satisfying conditions

asked 2013-03-24 12:35:39 -0500

sjcavazos2 gravatar image

Hi, I am looking for a function which will partition a list. For a simple example, suppose I have the list [1,2,3,4,5,6]. Suppose I want all the even integers in one list and the odd integers in another. Is there a function that can do this, and perhaps yeild something like [[1,3,5],[2,4,6]]? In this case, the number of partitions is 2, so it is fairly easy, but in my problem the number is not known. In mathematica, the function I want is called GatherBy.

edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted

answered 2013-03-24 13:15:40 -0500

fidbc gravatar image

For the particular example you have you can try

sage: l=range(10)
sage: odd=filter(lambda x: x%2, l)
sage: even=filter(lambda x: x%2==0, l)
sage: odd
[1, 3, 5, 7, 9]
sage: even
[0, 2, 4, 6, 8]

Otherwise you can try implementing a naive version of gather_by using dictionaries as follows

def gather_by( l, f ):
    parts = {}
    for e in l:
        cur_key = f(e)
        if parts.has_key( cur_key ):
            parts[cur_key].append( e )
            parts[cur_key] = [ e ]
    return parts.values()


sage: gather_by( range(10), lambda x: x%2)
[[0, 2, 4, 6, 8], [1, 3, 5, 7, 9]]
edit flag offensive delete link more


Perfect! Thanks!

sjcavazos2 gravatar imagesjcavazos2 ( 2013-03-24 13:50:23 -0500 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools


Asked: 2013-03-24 12:35:39 -0500

Seen: 43 times

Last updated: Mar 24 '13