Mercurial Hosting > traffic-intelligence
changeset 733:c35e4a4b199d dev
sortbylength
author | Nicolas Saunier <nicolas.saunier@polymtl.ca> |
---|---|
date | Tue, 11 Aug 2015 12:06:10 -0400 |
parents | ad31520e81b5 |
children | 1d4dcb5c8708 |
files | python/tests/utils.txt python/utils.py |
diffstat | 2 files changed, 20 insertions(+), 0 deletions(-) [+] |
line wrap: on
line diff
diff -r ad31520e81b5 -r c35e4a4b199d python/tests/utils.txt --- a/python/tests/utils.txt Tue Aug 11 11:49:01 2015 -0400 +++ b/python/tests/utils.txt Tue Aug 11 12:06:10 2015 -0400 @@ -50,6 +50,13 @@ >>> mostCommon([range(2), range(4), range(2)]) [0, 1] +>>> res = sortByLength([range(3), range(4), range(1)]) +>>> [len(r) for r in res] +[1, 3, 4] +>>> res = sortByLength([range(3), range(4), range(1), range(5)], reverse = True) +>>> [len(r) for r in res] +[5, 4, 3, 1] + >>> lcss = LCSS(similarityFunc = lambda x,y: abs(x-y) <= 0.1) >>> lcss.compute(range(5), range(5)) 5
diff -r ad31520e81b5 -r c35e4a4b199d python/utils.py --- a/python/utils.py Tue Aug 11 11:49:01 2015 -0400 +++ b/python/utils.py Tue Aug 11 12:06:10 2015 -0400 @@ -233,6 +233,19 @@ xsorted = sorted(D.keys()) return xsorted, [D[x] for x in xsorted] +def compareLengthForSort(i, j): + if len(i) < len(j): + return -1 + elif len(i) == len(j): + return 0 + else: + return 1 + +def sortByLength(instances, reverse = False): + '''Returns a new list with the instances sorted by length (method __len__) + reverse is passed to sorted''' + return sorted(instances, cmp = compareLengthForSort, reverse = reverse) + def ceilDecimals(v, nDecimals): '''Rounds the number at the nth decimal eg 1.23 at 0 decimal is 2, at 1 decimal is 1.3'''