Implementing python slice notation

前端 未结 6 552
轻奢々
轻奢々 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 05:58

    This is based on @ecatmur's Python code ported again to PHP.

    = $length) {
            $endpoint = $step < 0 ? $length - 1 : $length;
        }
        return $endpoint;
    }
    
    function mySlice($L, $start = null, $stop = null, $step = null) {
        $sliced = array();
        $length = count($L);
    
        // adjust_slice()
        if ($step === null) {
            $step = 1;
        }
        elseif ($step == 0) {
            throw new Exception('step cannot be 0');
        }
    
        if ($start === null) {
            $start = $step < 0 ? $length - 1 : 0;
        }
        else {
            $start = adjust_endpoint($length, $start, $step);
        }
    
        if ($stop === null) {
            $stop = $step < 0 ? -1 : $length;
        }
        else {
            $stop = adjust_endpoint($length, $stop, $step);
        }
    
        // slice_indices()
        $i = $start;
        $result = array();
        while ($step < 0 ? ($i > $stop) : ($i < $stop)) {
            $sliced []= $L[$i];
            $i += $step;
        }
        return $sliced;
    }
    

提交回复
热议问题