2

I try to convert the following Python function:

def Sous(dist,d):

    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

into a PHP function:

function sous($dist, $d){
    $l = count($dist);
    $L = [[]];
    foreach(range(0,$l) as $i){
        $K = [];
        $s = array_sum(array_slice($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;
}

And when I test it:

var_dump(sous([3,2,2,1,1,0], 2));

I get the error:

Uncaught Error: Unsupported operand types

for the line

$K[] = $p+$j;

And I don't know how to solve it, do you have any ideas?

2
  • Looks like $p is an array, and (in PHP) you can't just add a number to array with +. Commented Jan 16, 2021 at 9:42
  • i think the problem is that [j] doesn't mean $j in PHP, but what does it mean ? Commented Jan 16, 2021 at 9:54

1 Answer 1

2

Python's range(n) returns an array from 0 to n-1 while PHP's range($n, $m) returns an array from $n to $m, so you have to use range(0, $l -1) there.

Also K.append(p+[j]) should be converted to $K[] = $p+[$j]; since $j is not an array.

The following function should work:

function sous($dist, $d){
    $l = count($dist);
    $L = [[]];
    foreach(range(0,$l - 1) as $i){
        $K = [];
        $s = array_sum(array_slice($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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.