1 #!/usr/bin/env python 2 3 """ 4 Sequence operations. 5 6 Copyright (C) 2015 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 def _getitem(seq, index): 25 26 "Return the item or slice specified by 'index'." 27 28 if _isinstance(index, int): 29 index = _normalise_index(index, seq.__len__()) 30 return seq.__get_single_item__(index) 31 elif _isinstance(index, slice): 32 return seq.__getslice__(index.start, index.end) 33 else: 34 raise TypeError 35 36 def _getslice(seq, start, end=None): 37 38 "Return a slice starting from 'start', with the optional 'end'." 39 40 length = seq.__len__() 41 42 if start is None: 43 start = 0 44 else: 45 start = _normalise_index(start, length) 46 47 if end is None: 48 end = length 49 else: 50 end = _normalise_index(end, length) 51 52 result = [] 53 while start < end: 54 result.append(seq.__get_single_item__(start)) 55 start += 1 56 return result 57 58 def _get_absolute_index(index, length): 59 60 """ 61 Return the absolute index for 'index' given a collection having the 62 specified 'length'. 63 """ 64 65 if index < 0: 66 return length + index 67 else: 68 return index 69 70 def _normalise_index(index, length): 71 72 "Normalise 'index' for a collection having the specified 'length'." 73 74 return _min(length, _max(0, _get_absolute_index(index, length))) 75 76 def _max(x, y): 77 78 "Return the maximum of 'x' and 'y'." 79 80 if x >= y: 81 return x 82 else: 83 return y 84 85 def _min(x, y): 86 87 "Return the minimum of 'x' and 'y'." 88 89 if x <= y: 90 return x 91 else: 92 return y 93 94 def _tuple(l): pass 95 96 # vim: tabstop=4 expandtab shiftwidth=4