N
N
Nimph2020-08-22 15:24:40
Python
Nimph, 2020-08-22 15:24:40

What does compare=operator mean. lt in this code? And how does the compare operator work here?

In one Internet resource I found an implementation of merge sort:

import operator
def merge_sort(L, compare=operator.lt): 
    if len(L) < 2:
        return L[:] 
    else:
        middle = int(len(L) / 2)  
        left = merge_sort(L[:middle], compare) 
        right = merge_sort(L[middle:], compare)
        print(left)
        return merge(left, right, compare)

def merge(left, right, compare):
    result = []
    i, j = 0, 0
    while i < len(left) and j < len(right):
        if compare(left[i], right[j]):
            result.append(left[i])
            i += 1
        else:
            result.append(right[j])
            j += 1
    while i < len(left):
        result.append(left[i])
        i += 1
    while j < len(right):
        result.append(right[j])
        j += 1
    return result


From reading the documentation, I realized that operator.lt(a,b) is a comparison of variables, but I can’t understand how compare = operator.lt works, please help.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
T
Ternick, 2020-08-22
@Nimph

Python 3.6.6 (v3.6.6:4cf1f54eb7, Jun 27 2018, 03:37:03) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from operator import lt
>>> help(lt)
Help on built-in function lt in module _operator:

lt(...)
    lt(a, b) -- Same as a<b.

>>>

The documentation and python says that the function lt(a, b) is equivalent to a < b.
More questions ?
If you are happy with the answer, mark the answer as the answer :)

W
WarGot, 2015-06-01
@AntonEssential

You can make the header location to the desired new address after the logic is worked out.

header("Location: http://www.example.com/"); /* Redirect browser */

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question