Achala Dissanayake Achala Dissanayake -5 years ago 84
Python Question

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

def compare(a,b):
return cmp(b,a)

print (L[-2])
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,


Answer Source

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

def compare(a,b):
    print 'comparing ',a,b
    return cmp(b,a)


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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download