1 #!/usr/bin/env python 2 3 """ 4 Sequence operations. 5 6 Copyright (C) 2015, 2016 Paul Boddie <paul@boddie.org.uk> 7 8 This program is free software; you can redistribute it and/or modify it under 9 the terms of the GNU General Public License as published by the Free Software 10 Foundation; either version 3 of the License, or (at your option) any later 11 version. 12 13 This program is distributed in the hope that it will be useful, but WITHOUT 14 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS 15 FOR A PARTICULAR PURPOSE. See the GNU General Public License for more 16 details. 17 18 You should have received a copy of the GNU General Public License along with 19 this program. If not, see <http://www.gnu.org/licenses/>. 20 """ 21 22 from native import _isinstance 23 24 class sequence: 25 26 "A common base class for sequence types." 27 28 def __getitem__(self, index): 29 30 "Return the item or slice specified by 'index'." 31 32 # Normalise any integer indexes, converting negative indexes to positive 33 # ones. 34 35 if _isinstance(index, int): 36 index = _normalise_index(index, self.__len__()) 37 return self.__get_single_item__(index) 38 39 # Handle slices separately. 40 41 elif _isinstance(index, slice): 42 return self.__getslice__(index.start, index.end) 43 44 # No other kinds of objects are supported as indexes. 45 46 else: 47 raise TypeError 48 49 def __getslice__(self, start, end=None): 50 51 "Return a slice starting from 'start', with the optional 'end'." 52 53 length = self.__len__() 54 55 # Handle a null start as the first position, otherwise normalising any 56 # start index. 57 58 if start is None: 59 start = 0 60 else: 61 start = _normalise_index(start, length) 62 63 # Handle a null end as the first position after the end of the sequence, 64 # otherwise normalising any end index. 65 66 if end is None: 67 end = length 68 else: 69 end = _normalise_index(end, length) 70 71 result = [] 72 73 while start < end: 74 result.append(self.__get_single_item__(start)) 75 start += 1 76 77 return result 78 79 def _get_absolute_index(index, length): 80 81 """ 82 Return the absolute index for 'index' given a collection having the 83 specified 'length'. 84 """ 85 86 if index < 0: 87 return length + index 88 else: 89 return index 90 91 def _normalise_index(index, length): 92 93 "Normalise 'index' for a collection having the specified 'length'." 94 95 return _min(length, _max(0, _get_absolute_index(index, length))) 96 97 def _max(x, y): 98 99 "Return the maximum of 'x' and 'y'." 100 101 if x >= y: 102 return x 103 else: 104 return y 105 106 def _min(x, y): 107 108 "Return the minimum of 'x' and 'y'." 109 110 if x <= y: 111 return x 112 else: 113 return y 114 115 def _tuple(l): pass 116 117 # vim: tabstop=4 expandtab shiftwidth=4