0

I was wondering, how is value of item1 and item2 considered?

import functools

lst = [ 2, 1, 3, 6,0, 4, 5]

def compare(item1, item2):
    print item1, item2
    return (item1) - (item2)


print lst
sorted(lst, key=functools.cmp_to_key(compare))

The output is given below

[2, 1, 3, 6, 0, 4, 5]
1 2    
3 1
3 2
6 2
6 3
0 3
0 2
0 1
4 2
4 6
4 3
5 3
5 6
5 4
Out[25]: [0, 1, 2, 3, 4, 5, 6]

I want to know how and on what bases are the values of item1 and item2 are considered?

13
  • 2
    Have you checked the documentation? It explains what an old-style comparison function is, what a key function is, and how functools.cmp_to_key converts between the two. Commented Nov 26, 2017 at 2:18
  • 1
    @RajatRaj what do you mean? Algorithmically? Python implements Timsort so-named after its developer Tim Peters Commented Nov 26, 2017 at 2:22
  • 1
    @RajatRaj your use of the word "considered" here is unclear. They are compared using the comparator function that you defined as compare, having run through functool.cmp_to_key whose definition you said you read. If you're asking why it's comparing the two elements it's comparing and why in that order, well, I thought you said you knew that Python implements Timsort, because that's the algorithm it's following. Take a half hour and read the two links I left you again, because they answer all the questions you could possibly have about this topic. Commented Nov 26, 2017 at 2:30
  • 1
    For details like that, you'll need to research how Python's hybrid Timsort works. There's an article on it in Wikipedia. There's links to the article in Python's documentation (here's one of them). Commented Nov 26, 2017 at 2:46
  • 1
    The exact values being compared are implementation details of the sorting algorithm that are subject to change and shouldn't matter to you. If you really need to understand it to that level of detail you should read the existing documentation as @martineau suggests. Those details are outside the scope of a StackOverflow answer. Commented Nov 26, 2017 at 3:01

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.