Romain Charles
Romain Charles

Reputation: 79

Translate a Python list slice to PHP

I try to translate this function someone made to help me, but I only know PHP so I tried to translate it.

Python :

def Sous(dist,d) :
    # Étant donné une distribution et un entier d (pour différences),
    # retourne la liste des schémas de différences de d possibles
    # à partir de la distribution.
    l=len(dist)
    L=[[]]
    for i in range(l) :
        K=[]
        s=sum(dist[i+1:])
        for p in L :
            q=sum(p)
            m=max(d-q-s,0)
            M=min(dist[i],d-q)
            for j in range(m,M+1) :
                K.append(p+[j])
        L=K
    return L

PHP :

function sous($dist, $d){
    $l = count($dist);
    $L = [[]];
    foreach(range(0,$l) as $i){
        $K = [];
        $s = array_sum($dist[$i+1]);
        foreach($L as $p){
            $q = array_sum($p);
            $m = max($d-$q-$s, 0);
            $M = min($dist[$i], $d-$q);
            foreach(range($m, $M+1) as $j){
                $K[] = $p+$j;
            }
        }
        $L = $K;
    }
    return $L;
}

But there is this error:

array_sum() expects parameter 1 to be array, int given

Can you tell me why?

Upvotes: 0

Views: 73

Answers (1)

mkrieger1
mkrieger1

Reputation: 23192

You tried to translate dist[i+1:] in Python to $dist[$i+1] in PHP. But they are not equivalent.

The Python expression means: use the sublist (or slice) of dist starting from index i+1 until the end.

The PHP expression means: use the element of dist at index i+1.

According to https://www.php.net/manual/en/function.array-slice.php, the PHP code corresponding to this Python expression should be:

array_slice($dist, $i+1)

Upvotes: 1

Related Questions