Reputation: 92
Trying to convert the following PHP function to Python but getting the following error. What would be the working Python equivalent to the below PHP function?
line 140, in doDetectBigToSmall for scale in xrange(start_scale, scale > 1,scale = scale* scale_update): UnboundLocalError: local variable 'scale' referenced before assignment
PHP CODE:
protected function doDetectBigToSmall($ii, $ii2, $width, $height)
{
$s_w = $width/20.0;
$s_h = $height/20.0;
$start_scale = $s_h < $s_w ? $s_h : $s_w;
$scale_update = 1 / 1.2;
for ($scale = $start_scale; $scale > 1; $scale *= $scale_update) {
$w = (20*$scale) >> 0;
$endx = $width - $w - 1;
$endy = $height - $w - 1;
$step = max($scale, 2) >> 0;
$inv_area = 1 / ($w*$w);
for ($y = 0; $y < $endy; $y += $step) {
for ($x = 0; $x < $endx; $x += $step) {
$passed = $this->detectOnSubImage($x, $y, $scale, $ii, $ii2, $w, $width+1, $inv_area);
if ($passed) {
return array('x'=>$x, 'y'=>$y, 'w'=>$w);
}
} // end x
} // end y
} // end scale
return null;
}
PYTHON CODE:
def doDetectBigToSmall(self,ii, ii2, width, height):
s_w = width/20.0
s_h = height/20.0
start_scale = s_h if s_h < s_w else s_w
scale_update = 1 / 1.2
for scale in xrange(start_scale, scale > 1,scale = scale* scale_update):
w = (20*scale) >> 0
endx = width - w - 1
endy = height - w - 1
step = max(scale, 2) >> 0
inv_area = 1 / (w*w)
for y in xrange(0,y < endy,y = y + step):
for x in xrange(0, x < endx, x= x + step):
passed = self.detectOnSubImage(x, y, scale, ii, ii2, w, width+1, inv_area)
if (passed):
return {'x': x, 'y': y, 'w': w}
Upvotes: 0
Views: 303
Reputation: 392
This is happening because xrange is a function and you are passing an uninitialized value to it. Scale will not be initialized until after xrange is run and returns a value. Python generally used for loops to iterate over lists. I recommend rewriting your code using while loops.
Upvotes: 0
Reputation: 70602
You have no idea what xrange()
does ;-) So read the docs before you try it again. In the meantime, replace:
for scale in xrange(start_scale, scale > 1,scale = scale* scale_update):
with
scale = start_scale
while scale > 1:
and, at the end of the loop, add:
scale *= scale_update
All your other uses of xrange()
are similarly broken, but you have to make some effort to learn what it does.
Upvotes: 2
Reputation: 1
This works for me:
def strpos_r(haystack, needle):
positions = []
position = haystack.rfind(needle)
while position != -1:
positions.append(position)
haystack = haystack[:position]
position = haystack.rfind(needle)
return positions
Also, functions should not really handle input errors for you. You usually just return False or let the function throw an execution error.
Upvotes: 0