need help translating a PHP for statement to python

Paul Rubin http
Sat Jan 10 04:15:53 EST 2004


dmm at machinic.net (Davis Marques) writes:
> I'm translating some PHP scripts to Python and have hit a roadblock
> with a for statement.  If someone could explain to me how one should
> translate the multiple increment, evaluations, etc. in the first line
> I would appreciate it deeply ...
> 
> for ($y = 0, $x = $cx-$cy-1; $y <= $cy; ++$y,++$x) {
>     $prd = $q * $y_ar[$y] + $car;
>     $prd -= ($car = intval($prd / 1E7)) * 1E7;
>     if ($bar = (($x_ar[$x] -= $prd + $bar) < 0)) $x_ar[$x] += 1E7;
>     }

Python is more verbose than PHP when it comes to stuff like that.
You have to expand things:

    x = cx - cy - 1
    for y in xrange(cy+1):
         prd = q * y_ar[y] + car;
         car = intval(prd / 1E7)
         prd -= car * 1E7;
         x_ar[x] -= prd + bar
         bar = (x_ar[x] < 0)  # is this REALLY what you wanted?
         if bar: 
            x_ar[x] += 1E7;
         x += 1

You can more closely approximate the two parallel loops with the
iterzip function in the new itertools package, but that only works
with the latest Python versions.

I suspect that your if statement was actually supposed to say

     if (($bar = ($x_ar[$x] -= $prd + $bar)) < 0) $x_ar[$x] += 1E7;

but I don't know what you're really trying to do.



More information about the Python-list mailing list