Implementing python slice notation Implementing python slice notation python python

Implementing python slice notation


Here's a straight port of the C code:

def adjust_endpoint(length, endpoint, step):     if endpoint < 0:         endpoint += length         if endpoint < 0:             endpoint = -1 if step < 0 else 0     elif endpoint >= length:         endpoint = length - 1 if step < 0 else length     return endpointdef adjust_slice(length, start, stop, step):     if step is None:         step = 1     elif step == 0:         raise ValueError("step cannot be 0")     if start is None:         start = length - 1 if step < 0 else 0     else:         start = adjust_endpoint(length, start, step)     if stop is None:         stop = -1 if step < 0 else length     else:         stop = adjust_endpoint(length, stop, step)     return start, stop, stepdef slice_indices(length, start, stop, step):     start, stop, step = adjust_slice(length, start, stop, step)     i = start     while (i > stop) if step < 0 else (i < stop):         yield i         i += stepdef mySlice(L, start=None, stop=None, step=None):     return [L[i] for i in slice_indices(len(L), start, stop, step)]


This is what I came up with (python)

def mySlice(L, start=None, stop=None, step=None):    answer = []    if not start:        start = 0    if start < 0:        start += len(L)    if not stop:        stop = len(L)    if stop < 0:        stop += len(L)    if not step:        step = 1    if stop == start or (stop<=start and step>0) or (stop>=start and step<0):        return []    i = start    while i != stop:        try:            answer.append(L[i])            i += step        except:            break    return answer

Seems to work - let me know what you think

Hope it helps


This is a solution I came up with in C# .NET, maybe not the prettiest, but it works.

private object[] Slice(object[] list, int start = 0, int stop = 0, int step = 0){    List<object> result = new List<object>();    if (step == 0) step = 1;    if (start < 0)    {        for (int i = list.Length + start; i < list.Length - (list.Length + start); i++)        {            result.Add(list[i]);        }    }    if (start >= 0 && stop == 0) stop = list.Length - (start >= 0 ? start : 0);    else if (start >= 0 && stop < 0) stop = list.Length + stop;    int loopStart = (start < 0 ? 0 : start);    int loopEnd = (start > 0 ? start + stop : stop);    if (step > 0)    {        for (int i = loopStart; i < loopEnd; i += step)            result.Add(list[i]);    }    else if (step < 0)    {        for (int i = loopEnd - 1; i >= loopStart; i += step)            result.Add(list[i]);    }    return result.ToArray();}