<p dir="ltr"><br>
On 5 Jul 2013 09:29, "Helmut Jarausch" <<a href="mailto:jarausch@igpm.rwth-aachen.de">jarausch@igpm.rwth-aachen.de</a>> wrote:<br>
><br>
> Hi,<br>
><br>
> I have coded a simple algorithm to solve a Sudoku (probably not the first one).<br>
> Unfortunately, it takes 13 seconds for a difficult problem which is more than 75 times slower<br>
> than the same algorithm coded in C++.<br>
> Is this to be expected or could I have made my Python version faster *** without *** sacrificing readability.<br>
> Profiling shows that the function find_good_cell is called (only) 45267 times and this take 12.9 seconds<br>
> CPU time (on a 3.2 GHz machine)</p>
<p dir="ltr">[Skipping to bottleneck]</p>
<p dir="ltr">> def find_good_cell() :</p>
<p dir="ltr">In this function you are accessing global variables a lot of times. Since accessing globals takes much more time than accessing locals, I advise you to assign them to local names, and use them.</p>
<p dir="ltr">>   Best= None<br>
>   minPoss= 10<br>
>   for r in range(9) :<br>
>     for c in range(9) :<br>
>       if  Grid[r,c] > 0 : continue<br>
>       Sq_No= (r//3)*3+c//3<br>
>       Possibilities= 0<br>
>       for d in range(1,10) :</p>
<p dir="ltr">On this condition (below) you can try to check which condition is True more often and put that condition first in order to take advantage of short circuiting and minimize array access.</p>
<p dir="ltr">>         if Row_Digits[r,d] or Col_Digits[c,d] or Sqr_Digits[Sq_No,d] : continue<br>
>         Possibilities+= 1<br>
><br>
>       if ( Possibilities < minPoss ) :<br>
>         minPoss= Possibilities<br>
>         Best= (r,c)<br>
><br>
>   if minPoss == 0 : Best=(-1,-1)<br>
>   return Best</p>
<p dir="ltr">Well I think that is as far as I go with my knowledge. Someone who knows numpy arrays' performance traits should be able to help you more.</p>