On 10/6/2010 7:14 AM, Antoon Pardon wrote:
That right-hand-half-open intervals (i.e. a<= i< b, equivalently [a, b) ), which are what Python uses, are to be preferred. (See aforelinked PDF: http://www.cs.utexas.edu/users/EWD/ewd08xx/EWD831.PDF)
This specifically discusses subsequences of 'natural numbers'.
The problem is that the slice notation is sometimes handy in situations where an open interval doesn't allow easily to mark what you want. For instance I have at one time implemted a Tree. This is a dict like structure but it allows to visit the keys in order. Because there is an order, slice notation can make sense. e.g. if T is a tree with names as keys, T['bea':'mike'] is a subtree where we have for each key that 'bea'<= key< 'mike'.
But what if I wanted a subtree where 'mike' was still included, but nothing further? Or what if the keys were floats or tuples and I wanted an inclusive upper boundary?
Strings and tuples are not natural numbers, but do have least members ('' and ()), so the bottom end had better be closed. Since substracting strings and tuples in meaningless, the argument of having stop-start == number of items does not apply. Floats can be subtracted, but the result in not a count of included items. So write the .__getitem__ method of *your* class how it best fits your use-cases.
Just be aware that an inclusive upper boundary means that s[a:b]+s[b:c] will no longer be s[a:c] because b will be duplicated. Let me also point out integer slices for builtins are adjusted to that they refer to actual slice positions. This is harder to do with strings;-). Also, suppose you want all strings beginning with 'a' or 'b'. With an open upper end, Tree['a':'c'] will do that. With closed upper end, you would need Tree['a':'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'] or somesuch.
And what if you needed the reverse sequence. If you start with inclusive limit, the reverse of a<= item<= b is b>= item>= a. If the second limit is to be exclusive the reverse of a<= item< b becomes (b - 1)>= item> (a - 1).
Slices with positive strides can be defined and understood in terms of slice positions before the first item, between all successive pairs of items and after the last. By this same definition and understanding, s[b:a:-1] should be reversed(s[a:b]), which is what many expect. It is not because the definition is given in terms of the translation into indexes and blindly applied to the case of negative strides without the needed adjustment. I consider this a design mistake, at least for many uses. (Extended slices, if not extended slicing, were added for numerical Python and they may have wanted the current definition for negative strides.)
-- Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list