Utilities: add 'sample' command, a basic interface to random.sample()

Also add tests for it.
This commit is contained in:
Daniel Folkinshteyn 2010-06-03 12:52:48 -04:00
parent 108f7f2f86
commit 52b36555f4
2 changed files with 19 additions and 1 deletions

View File

@ -86,12 +86,24 @@ class Utilities(callbacks.Plugin):
def shuffle(self, irc, msg, args, things):
"""<arg> [<arg> ...]
Shuffles the arguments given it.
Shuffles the arguments given.
"""
random.shuffle(things)
irc.reply(' '.join(things))
shuffle = wrap(shuffle, [many('anything')])
def sample(self, irc, msg, args, num, things):
"""<num> <arg> [<arg> ...]
Randomly chooses <num> items out of the arguments given.
"""
try:
samp = random.sample(things, num)
irc.reply(' '.join(samp))
except ValueError, e:
irc.error('%s' % (e,))
sample = wrap(sample, ['positiveInt', many('anything')])
def apply(self, irc, msg, args, command, rest):
"""<command> <text>

View File

@ -59,4 +59,10 @@ class UtilitiesTestCase(PluginTestCase):
def testShuffle(self):
self.assertResponse('shuffle a', 'a')
def testSample(self):
self.assertResponse('sample 1 a', 'a')
self.assertError('sample moo')
self.assertError('sample 5 moo')
self.assertRegexp('sample 2 a b c', '^[a-c] [a-c]$')
# vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79: