Implementing python slice notation

前端 未结 6 569
轻奢々
轻奢々 2021-02-07 05:06

I\'m trying to reimplement python slice notation in another language (php) and looking for a snippet (in any language or pseudocode) that would mimic the python logic. That is,

6条回答
  •  时光取名叫无心
    2021-02-07 06:05

    I've written a PHP port based on the C code, optimized for step sizes -1 and 1:

    function get_indices($length, $step, &$start, &$end, &$size)
    {
            if (is_null($start)) {
                    $start = $step < 0 ? $length - 1 : 0;
            } else {
                    if ($start < 0) {
                            $start += $length;
                            if ($start < 0) {
                                    $start = $step < 0 ? -1 : 0;
                            }
                    } elseif ($start >= $length) {
                            $start = $step < 0 ? $length - 1 : $length;
                    }
            }
    
            if (is_null($end)) {
                    $end = $step < 0 ? -1 : $length;
            } else {
                    if ($end < 0) {
                            $end += $length;
                            if ($end < 0) {
                                    $end = $step < 0 ? - 1 : 0;
                            }
                    } elseif ($end >= $length) {
                            $end = $step < 0 ? $length - 1 : $length;
                    }
            }
    
            if (($step < 0 && $end >= $start) || ($step > 0 && $start >= $end)) {
                    $size = 0;
            } elseif ($step < 0) {
                    $size = ($end - $start + 1) / $step + 1;
            } else {
                    $size = ($end - $start - 1) / $step + 1;
            }
    }
    
    function mySlice($L, $start = NULL, $end = NULL, $step = 1)
    {
            if (!$step) {
                    return false; // could throw exception too
            }
            $length = count($L);
            get_indices($length, $step, $start, $end, $size);
    
            // optimize default step
            if ($step == 1) {
                    // apply native array_slice()
                    return array_slice($L, $start, $size);
            } elseif ($step == -1) {
                    // negative step needs an array reversal first
                    // with range translation
                    return array_slice(array_reverse($L), $length - $start - 1, $size);
            } else {
                    // standard fallback
                    $r = array();
                    for ($i = $start; $step < 0 ? $i > $end : $i < $end; $i += $step) {
                            $r[] = $L[$i];
                    }
                    return $r;
            }
    }
    

提交回复
热议问题