gaurav
gaurav

Reputation: 15

python implementation of c++ sort

    struct node {
        int L, R, i;
    }q[N];

    bool cmp(node x, node y) {
        if(x.L/BLOCK != y.L/BLOCK) {
            // different blocks, so sort by block.
            return x.L/BLOCK < y.L/BLOCK;
        }
        // same block, so sort by R value
        return x.R < y.R;
    }
sort(q, q + m, cmp);

where m is the size of q array.I want to know how to implement the above c++ code in python i.e compare on basis of function as third argument.

Upvotes: 0

Views: 813

Answers (2)

Christoph Burschka
Christoph Burschka

Reputation: 4689

As of 3.0, Python no longer supports using cmp functions in its built-in sorting, only a key function that is expected to map the values to comparable keys.

Previously, you would use:

def cmp(x, y):
    if (x > y):
        return 1
    elif (x < y):
        return -1
    else:
        return 0

sorted([1,3,5,2,4,6], cmp=cmp)

If you don't have a key function available, but only a cmp function, Python has an adaptor function in the functools module:

from functools import cmp_to_key

def cmp(x, y):
    if (x > y):
        return 1
    elif (x < y):
        return -1
    else:
        return 0

sorted([1,3,5,2,4,6], key=cmp_to_key(cmp)

Upvotes: 0

Green Cloak Guy
Green Cloak Guy

Reputation: 24691

You're using a struct q to represent some data. I'm going to assume that you've create an object of the requisite type in python:

class Q: 
  def __init__(self, L, R, i):
    self.L = L
    self.R = R
    self.i = i

I'm also going to assume that you've defined BLOCK already, and that it's a constant.

So, given you have a list q of objects of type Q, you would sort that list by doing

q.sort(lambda x: (x.L/BLOCK, x.R))

that is, calling sort() with a lambda function which returns the 2-tuple for any given element of q. When a sorting key in python returns a tuple, the sort goes in priority order based on that tuple - if x.L/BLOCK is equal, only then does it proceed to using x.R for comparison.

Both list.sort() and the built-in function sorted() take an optional argument that is a function/lambda "key". This key outputs the criteria on which to sort, for any given element - similar to the third parameter of std::sort in C++, except it uses a key function instead of a comparator. In this case, that works just as well, though.

Upvotes: 1

Related Questions