Achala Dissanayake Achala Dissanayake - 5 months ago 7
Python Question

What happens when a python function that takes arguments called without defining parameters?

L=[5,10,4,2,8,7]
def compare(a,b):
return cmp(b,a)

L.sort(compare)
print (L[-2])
L.sort()
print (L[2])


When this code is run, why a exception is not thrown since the function compare called within sort function has not been given exactly two arguments?
when the code is run it gives the output as,

4
5

Answer

You are not calling directly the function

You are passing to the sort function a 'pointer' or a 'reference' to the function that will be used as a comparator

if you need more debugging info add a line that print what is being compared as follow

L=[5,10,4,2,8,7]
def compare(a,b):
    print 'comparing ',a,b
    return cmp(b,a)

L.sort(compare)

and you will also notice that the number of calls depends on L dis-order

there are several ways to solve the problem of order an array some of that are merge-sort , binary-sort and still others

this is the link to the source code of python list object