Shashank
Shashank

Reputation: 1135

Python reverse sort() vs sort() with negative values

I was trying to sort the given input on the basis of maximum number value in front of name (descending order). For example:

3                                 <-- Number of test case

shank 3

shashank 3

friend 5

In code when I used c.sort(reverse = True) :

a = int(raw_input())
c = []
for _ in xrange(a):
    a,b = raw_input().split()
    b = int(b)
    c.append((b,a))
c.sort(reverse = True)
print c

Output :

[(5, 'friend'), (3, 'shashank'), (3, 'shank')]

Which is absolutely fine.

Now for different approach I tried making integer (b in code) negative due to which more negative integer will come first means it will work as reverse. In output the arrangement of numbers is fine but the string is not matching with previous output.

Code:

a = int(raw_input())
c = []
for _ in xrange(a):
    a,b = raw_input().split()
    b = int(b)
    c.append((-b,a)) 
c.sort()
print c

Output :

[(-5, 'friend'), (-3, 'shank'), (-3, 'shashank')]

Which is different from previous one as shank came first and then shashank came.

So what is really happening behind this ? Why it is giving different output ?

Upvotes: 0

Views: 439

Answers (1)

TigerhawkT3
TigerhawkT3

Reputation: 49330

With c.append((-b,a)), you inverted b but not a, so when two items have the same b, they are sorted in ascending a order.

Upvotes: 3

Related Questions