user11682081
user11682081

Reputation:

How to fix 'TypeError: invalid keyword argument for sort()'

Order a list of 2-dimensional points using the compare_points function.

I don't understand how to pass the compare_points function to the sort() method.

def compare_points( p, q ):
    if p[0] < q[0] or (p[0] == q[0] and p[1] < q[1]):
        return -1
    elif p[0] > q[0] or (p[0] == q[0] and p[1] > q[1]):
        return 1
    else:
        return 0

#print(compare_points( [1,3], [5,6])) # outputs -1
#print(compare_points( [1,3], [1,6])) # ouputs -1
#print(compare_points( [1,3], [1,3])) # outputs 0
#print(compare_points( [1,3], [0,3])) # outputs 1


L = [ [5,8], [5,2], [12, 3], [1,3], [10,2], [12,1], [12,3] ]
L.sort(cmp=compare_points)
print(L)

Actual results:

L.sort(cmp=compare_points)
builtins.TypeError: 'cmp' is an invalid keyword argument for sort()

Expected results:

L = [ [1,3], [5,2], [5,8], [10,2], [12,1], [12,3], [12,3] ]

Upvotes: 3

Views: 4704

Answers (2)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477210

There is actually no need at all here to specify a key, since what you define here, is basically just lexicographical order, which is the standard way a list is ordered in Python.

You thus can sort without specifying a key, like:

>>> L = [ [5,8], [5,2], [12, 3], [1,3], [10,2], [12,1], [12,3] ]
>>> L.sort()
>>> L
[[1, 3], [5, 2], [5, 8], [10, 2], [12, 1], [12, 3], [12, 3]]

In , the .sort(…) [python-doc] function could indeed take a cmp=... parameter that was a comparator between two values. Since , this parameter has been removed.

Sorting with a key is more effective, since it avoids that you implement a comparison function that is invalid: a comparison function should be reflexive, antisymmetric, and transitive. Some comparison functions did not meet those conditions.

Upvotes: 6

You are using Python3 in python3, the keyword argument is key, so you should do

L.sort(key=compare_points)

If you want to do it with the cmp keyword argument, you should use Python2

Upvotes: 1

Related Questions