Sunday, September 29, 2013

slice an array python style

   +---+---+---+---+---+
   | H | e | l | p | A |
   +---+---+---+---+---+
     0   1   2   3   4   5
-6  -5  -4  -3  -2  -1

python slice style:
  1. start index is included, end index is excluded
  2. no start, end index values or -ve start, end index values can be specified, -ve and +ve start, end index values can be specified
  3. for invalid inputs, handle gracefully (especially end index value)
  4. for +ve step, traverse forward; for -ve step, traverse backward
Hints:
  1. for step > 0, defaults are start = 0, end = array.length (5)
  2. for step < 0, defaults are start = -1, end = -array.length-1 (-6)
//    +---+---+---+---+---+
//    | H | e | l | p | A |
//    +---+---+---+---+---+
//      0   1   2   3   4   5
// -6  -5  -4  -3  -2  -1
int[] slice(int[] a, int? START, int? END, int step):
    if a == null : return empty
    if step == 0 : 
        return empty
    else if step > 0 :
        start = 0
        end = a.length
    else // step < 0
        start = -1
        end = -a.length -1
    start = START ?? start
    end = END ?? end
    if start < -a.length || start >= a.length : return empty
    if end < -a.length -1 : end = -a.length -1
    if end > a.length : end = a.length
    start = toPositiveIndex(start, a.length)
    end = toPositiveIndex(end, a.length)
    if step > 0 && start > end : return empty
    if step < 0 && start < end : return empty
    slicelength = ceiling(end - start / step)
    for (i = start; (step > 0 ? i < end : i > end); i += step)
        slice[j++] = a[i]
    return slice

int toPositiveIndex(int index, int length):
    return index >= 0 ? index : index + length

tests:
s e step slice
-------------------------------
0 5 1 {HelpA}
? ? 1 {HelpA}
0 ? 1 {HelpA}
? 5 1 {HelpA}
0 >5 1 {HelpA}
-5 5 1 {HelpA}
0 1 1 {H}
-3 5 1 {lpA}
0 0 1 {} 
1 0 1 {}
? ? 2 {HlA}

? ? -1 {ApleH}
? -6 -1 {ApleH}
-1 ? -1 {ApleH}
-1 -6 -1 {ApleH}
-1 <-6 -1 {ApleH}
4 -6 -1 {ApleH}
0 -6 -1 {H}
0 0 -1 {} 
0 1 -1 {}
? ? -2 {AlH}

No comments:

Post a Comment