Fredrik Johansson wrote: > Consider sorting a list of pairs representing fractions. This can be > done easily in Python 2.x with the comparison function lambda > (p,q),(r,s): cmp(p*s, q*r). In Python 2.6, this is about 40 times > faster than using fractions.Fraction as a key function. [steve at sylar ~]$ python2.7 -m timeit -s "L = [(1,2), (3,4), (0,5), (9,100), (3,7), (2,8)]" "sorted(L, lambda (p,q),(r,s): cmp(p*s, q*r))" 10000 loops, best of 3: 25.1 usec per loop [steve at sylar ~]$ python2.7 -m timeit -s "L = [(1,2), (3,4), (0,5), (9,100), (3,7), (2,8)]" -s "from fractions import Fraction" "sorted(L, key=lambda t: Fraction(*t))" 1000 loops, best of 3: 236 usec per loop So for a short list, I get a factor of ten difference. For a longer list, I'd expect the key function to win out. Much to my astonishment, it doesn't -- I get similar results regardless of the size of L. Size of L key/cmp ========== ========= 6 9.4 600 13.9 60000 7.0 6000000 6.7 -- Steven
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4