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?
Advertisement
Answer
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; }