Added sortBy, which uses the decorate/sort/undecorate pattern to sort by a certain criteria.

This commit is contained in:
Jeremy Fincher 2003-09-03 08:51:45 +00:00
parent 64c97a7c98
commit a764de50ad
2 changed files with 24 additions and 0 deletions

View File

@ -265,6 +265,10 @@ def findBinaryInPath(s):
return cmdLine return cmdLine
def commaAndify(seq): def commaAndify(seq):
"""Given a a sequence, returns an english clause for that sequence.
I.e., given [1, 2, 3], returns '1, 2, and 3'
"""
L = list(seq) L = list(seq)
if len(L) == 0: if len(L) == 0:
return '' return ''
@ -278,6 +282,7 @@ def commaAndify(seq):
_unCommaTheRe = re.compile(r'(.*),\s*(the)$', re.I) _unCommaTheRe = re.compile(r'(.*),\s*(the)$', re.I)
def unCommaThe(s): def unCommaThe(s):
"""Takes a string of the form 'foo, the' and turns it into 'the foo'."""
m = _unCommaTheRe.match(s) m = _unCommaTheRe.match(s)
if m is not None: if m is not None:
return '%s %s' % (m.group(2), m.group(1)) return '%s %s' % (m.group(2), m.group(1))
@ -285,6 +290,7 @@ def unCommaThe(s):
return s return s
def wrapLines(s): def wrapLines(s):
"""Word wraps several paragraphs in a string s."""
L = [] L = []
for line in s.splitlines(): for line in s.splitlines():
L.append(textwrap.fill(line)) L.append(textwrap.fill(line))
@ -292,6 +298,9 @@ def wrapLines(s):
plurals = {} plurals = {}
def pluralize(i, s): def pluralize(i, s):
"""Returns the plural of s based on its number i. Put any exceptions to
the general English rule of appending 's' in the plurals dictionary.
"""
if i == 1: if i == 1:
return s return s
else: else:
@ -301,10 +310,18 @@ def pluralize(i, s):
return s + 's' return s + 's'
def be(i): def be(i):
"""Returns the form of the verb 'to be' based on the number i."""
if i == 1: if i == 1:
return 'is' return 'is'
else: else:
return 'are' return 'are'
def sortBy(f, L, cmp=cmp):
"""Uses the decorate-sort-undecorate pattern to sort L by function f."""
for (i, elt) in enumerate(L):
L[i] = (f(elt), elt)
L.sort(cmp)
for (i, elt) in enumerate(L):
L[i] = L[i][1]
# vim:set shiftwidth=4 tabstop=8 expandtab textwidth=78: # vim:set shiftwidth=4 tabstop=8 expandtab textwidth=78:

View File

@ -163,5 +163,12 @@ class UtilsTest(unittest.TestCase):
self.assertEqual(utils.normalizeWhitespace('foo\nbar'), 'foo bar') self.assertEqual(utils.normalizeWhitespace('foo\nbar'), 'foo bar')
self.assertEqual(utils.normalizeWhitespace('foo\tbar'), 'foo bar') self.assertEqual(utils.normalizeWhitespace('foo\tbar'), 'foo bar')
def testSortBy(self):
L = ['abc', 'z', 'AD']
utils.sortBy(len, L)
self.assertEqual(L, ['z', 'AD', 'abc'])
utils.sortBy(str.lower, L)
self.assertEqual(L, ['abc', 'AD', 'z'])
# vim:set shiftwidth=4 tabstop=8 expandtab textwidth=78: # vim:set shiftwidth=4 tabstop=8 expandtab textwidth=78: