Ask Your Question
0

Partition list satisfying conditions

asked 12 years ago

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.

Preview: (hide)

1 Answer

Sort by » oldest newest most voted
1

answered 12 years ago

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 )
        else:
            parts[cur_key] = [ e ]
    return parts.values()

Then

sage: gather_by( range(10), lambda x: x%2)
[[0, 2, 4, 6, 8], [1, 3, 5, 7, 9]]
Preview: (hide)
link

Comments

Perfect! Thanks!

sjcavazos2 gravatar imagesjcavazos2 ( 12 years ago )

Your Answer

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

Add Answer

Question Tools

Stats

Asked: 12 years ago

Seen: 336 times

Last updated: Mar 24 '13