[Tutor] all elements equal in tuple or list
Kent Johnson
kent37 at tds.net
Fri Nov 19 03:58:43 CET 2004
Kent Johnson wrote:
> It will also return true if vals is the number 0 so maybe it is a bit
> over broad, but anyway that is the idea.
I decided to write a version of this that behaves 'correctly' for all
inputs. What 'correct' means to me is, if the input is not iterable, the
function raises an exception; if the input is an empty iterable, the
function returns True; otherwise it compares the first element to all
the others and reports the result.
To test for an iterable, I use the typical Python 'Easier to ask
forgiveness than permission' idiom - rather than trying to figure out if
vals is iterable, I just try to get an iterator from it. If it fails I
let the exception propagate out of the function.
To allow for empty iterables, I catch the StopIteration that i.next()
will raise and just return True.
For good measure I threw in some unit tests - everyone reading this list
should be learning how to write unit tests, right? :-)
OK maybe I got a little carried away on the unit tests...
Kent
##############################3
import itertools, unittest
def allTheSame(vals):
''' Test if vals is an iterable whose elements are all equal. '''
i = iter(vals) # Raises TypeError if vals is not a sequence
try:
first = i.next()
except StopIteration:
# vals is an empty sequence
return True
for item in i:
if first != item:
return False
return True
if __name__ == '__main__':
class Test(unittest.TestCase):
def testLists(self):
self.assert_(allTheSame([]))
self.assert_(allTheSame([1]))
self.assert_(allTheSame([1, 1, 1, 1]))
self.failIf(allTheSame([1, 1, 2, 1]))
self.failIf(allTheSame([2, 1, 1]))
def testTuples(self):
self.assert_(allTheSame(()))
self.assert_(allTheSame((1,)))
self.assert_(allTheSame((1, 1, 1, 1)))
self.failIf(allTheSame((1, 1, 2, 1)))
self.failIf(allTheSame((2, 1, 1)))
def testStrings(self):
self.assert_(allTheSame(""))
self.assert_(allTheSame("1"))
self.assert_(allTheSame("1111"))
self.failIf(allTheSame("1121"))
self.failIf(allTheSame("211"))
def testDicts(self):
# dicts are iterable too
self.assert_(allTheSame( {} ))
self.assert_(allTheSame( { 1:1, 1:1 }))
self.failIf(allTheSame( { 1:1, 2:2 } ))
def testNonSequence(self):
self.assertRaises(TypeError, allTheSame, None)
self.assertRaises(TypeError, allTheSame, 0)
self.assertRaises(TypeError, allTheSame, 0.0)
unittest.main()
More information about the Tutor
mailing list