|
| 1 | +# test_builtin.py:BuiltinTest.test_filter() |
| 2 | +from libtest import assertRaises |
| 3 | + |
| 4 | +doc="filter" |
| 5 | +class Squares: |
| 6 | + def __init__(self, max): |
| 7 | + self.max = max |
| 8 | + self.sofar = [] |
| 9 | + |
| 10 | + def __len__(self): return len(self.sofar) |
| 11 | + |
| 12 | + def __getitem__(self, i): |
| 13 | + if not 0 <= i < self.max: raise IndexError |
| 14 | + n = len(self.sofar) |
| 15 | + while n <= i: |
| 16 | + self.sofar.append(n*n) |
| 17 | + n += 1 |
| 18 | + return self.sofar[i] |
| 19 | + |
| 20 | +assert list(filter(lambda c: 'a' <= c <= 'z', 'Hello World')) == list('elloorld') |
| 21 | +assert list(filter(None, [1, 'hello', [], [3], '', None, 9, 0])) == [1, 'hello', [3], 9] |
| 22 | +assert list(filter(lambda x: x > 0, [1, -3, 9, 0, 2])) == [1, 9, 2] |
| 23 | +assert list(filter(None, Squares(10))) == [1, 4, 9, 16, 25, 36, 49, 64, 81] |
| 24 | +assert list(filter(lambda x: x%2, Squares(10))) == [1, 9, 25, 49, 81] |
| 25 | +def identity(item): |
| 26 | + return 1 |
| 27 | +filter(identity, Squares(5)) |
| 28 | +assertRaises(TypeError, filter) |
| 29 | +class BadSeq(object): |
| 30 | + def __getitem__(self, index): |
| 31 | + if index<4: |
| 32 | + return 42 |
| 33 | + raise ValueError |
| 34 | +assertRaises(ValueError, list, filter(lambda x: x, BadSeq())) |
| 35 | +def badfunc(): |
| 36 | + pass |
| 37 | +assertRaises(TypeError, list, filter(badfunc, range(5))) |
| 38 | + |
| 39 | +# test bltinmodule.c::filtertuple() |
| 40 | +assert list(filter(None, (1, 2))) == [1, 2] |
| 41 | +assert list(filter(lambda x: x>=3, (1, 2, 3, 4))) == [3, 4] |
| 42 | +assertRaises(TypeError, list, filter(42, (1, 2))) |
| 43 | + |
| 44 | +doc="finished" |
0 commit comments