1

I have a list of tuples that I want to sort based on a fraction of two of the elements in the tuple. The problem I'm running into, is that Python's sort() method for lists appears to not work on fractions.

Before: A: [(4, 1, 0), (4, 1, 1), (1, 1, 2), (4, 7, 3), (2, 4, 4), (1, 4, 5), (3, 1, 6), (2, 1, 7), (3, 9, 8), (1, 6, 9)]
After:  A: [(1, 6, 9), (1, 4, 5), (3, 9, 8), (2, 4, 4), (1, 1, 2), (4, 7, 3), (4, 1, 0), (4, 1, 1), (3, 1, 6), (2, 1, 7)]

The code that's doing the sorting:

print("A: " + str(A))
A.sort(key=lambda tup: long(tup[1]/tup[0]), reverse=True)
print("A: " + str(A))

I think that according to the above code, the element (1,1,2), and the element (4,7,3) should be switched, because 7/4 > 1/1. I'm also pretty sure that all of the fractions at the end are wrong, which makes me think it's just doing integer division, and rounding. I thought casting it to a long might fix this, but it did not.

Derek Halden
  • 2,223
  • 4
  • 17
  • 26

1 Answers1

3

In Python 2 / on integers does integer division (truncating the result). What you have tried to do is to then cast that result to a long but the division is already done and the information lost. Try to cast only the first argument, and cast it to float instead:

A.sort(key=lambda tup: float(tup[1])/tup[0], reverse=True)

/ is now changed in Python 3 to always do float division.

Emil Vikström
  • 90,431
  • 16
  • 141
  • 175
  • I think it should be float, but yes, it worked with that change, thanks! – Derek Halden May 09 '16 at 06:58
  • …and integer division is done using `//` in python3. – spectras May 09 '16 at 06:59
  • 1
    There's also always `from __future__ import division`. FWIW, I highly recommend it :-) – mgilson May 09 '16 at 07:02
  • 1
    @spectras -- Integer division is done using `//` in python2.x too. It's just an unfortunatly mistake that `/` _also_ does integer division when it has integer arguments on python2.x :-P. Mostly I point this out so that people reading your comment don't think ... "Oh, I'm using python2.x, I guess I should use `/` for integer division then". – mgilson May 09 '16 at 07:03
  • @mgilson> good pointing this out. It will make transition to python3 of that code easier as well. – spectras May 09 '16 at 07:07