从python到PHP的For循环转换问题
我尝试转换以下Python函数:从python到PHP的For循环转换问题,python,php,for-loop,type-conversion,Python,Php,For Loop,Type Conversion,我尝试转换以下Python函数: 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)
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
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;
}
进入PHP函数:
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
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;
}
当我测试它时:
var_dump(sous([3,2,2,1,1,0], 2));
我得到一个错误:
Uncaught Error: Unsupported operand types
排队
$K[] = $p+$j;
我不知道如何解决它,你有什么想法吗?Python的range(n)
返回一个从0
到n-1
的数组,而PHP的range($n,$m)
返回一个从$n
到$m
的数组,所以你必须在那里使用range(0,$l-1)
另外,K.append(p+[j])
应转换为$K[]=$p+[$j]
因为$j
不是数组
以下功能应起作用:
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;
}
看起来,
$p
是一个数组,而且(在PHP中)不能仅仅用+
向数组中添加一个数字。我认为问题在于[j]在PHP中并不意味着$j,但它意味着什么?