|
| 1 | +# test_builtin.py:BuiltinTest.test_map() |
| 2 | +from libtest import assertRaises |
| 3 | + |
| 4 | +doc="map" |
| 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(map(lambda x: x*x, range(1,4))) == [1, 4, 9] |
| 21 | +try: |
| 22 | + from math import sqrt |
| 23 | +except ImportError: |
| 24 | + def sqrt(x): |
| 25 | + return pow(x, 0.5) |
| 26 | +assert list(map(lambda x: list(map(sqrt, x)), [[16, 4], [81, 9]])) == [[4.0, 2.0], [9.0, 3.0]] |
| 27 | +assert list(map(lambda x, y: x+y, [1,3,2], [9,1,4])) == [10, 4, 6] |
| 28 | + |
| 29 | +def plus(*v): |
| 30 | + accu = 0 |
| 31 | + for i in v: accu = accu + i |
| 32 | + return accu |
| 33 | +assert list(map(plus, [1, 3, 7])) == [1, 3, 7] |
| 34 | +assert list(map(plus, [1, 3, 7], [4, 9, 2])) == [1+4, 3+9, 7+2] |
| 35 | +assert list(map(plus, [1, 3, 7], [4, 9, 2], [1, 1, 0])) == [1+4+1, 3+9+1, 7+2+0] |
| 36 | +assert list(map(int, Squares(10))) == [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] |
| 37 | +def Max(a, b): |
| 38 | + if a is None: |
| 39 | + return b |
| 40 | + if b is None: |
| 41 | + return a |
| 42 | + return max(a, b) |
| 43 | +assert list(map(Max, Squares(3), Squares(2))) == [0, 1] |
| 44 | +assertRaises(TypeError, map) |
| 45 | +assertRaises(TypeError, map, lambda x: x, 42) |
| 46 | +class BadSeq: |
| 47 | + def __iter__(self): |
| 48 | + raise ValueError |
| 49 | + yield None |
| 50 | +assertRaises(ValueError, list, map(lambda x: x, BadSeq())) |
| 51 | +def badfunc(x): |
| 52 | + raise RuntimeError |
| 53 | +assertRaises(RuntimeError, list, map(badfunc, range(5))) |
| 54 | +doc="finished" |
0 commit comments