[Tutor] Creatively solving math problems -----help

Jeff Shannon jeff at ccvcorp.com
Thu Sep 11 11:50:23 EDT 2003


Clay Shirky wrote:
>>for x in range(20000):
>>      if [x%y for y in range(2, 7)] == 1 and x % 7 == 0:
>>              print x
> 
> 
> This is awfully hard to read -- any reason you're trying to cram so much
> stuff on one line? Is this what you are trying to do?
> 
> for x in range(20000):
>     for y in range(2, 7):
>         if x % y == 1 and x % 7 == 0:
>             print x
>             break
> 
> If so, it will be easy to start altering from there.

Another thing to consider here -- you've got two loops ('for x...' and 
'for y...'), and a compound 'if' statement.  Note that one half of the 
'if' statement (and thus the entire test) will be true for only one 
value in seven of the outer loop, and that the value of the inner loop 
makes *no* difference to this.  This means that, by splitting into two 
if statements, we can run the inner loop one-seventh as many times.

for x in range(20000):
     if x % 7 == 0:
         for y in range(2, 7):
             if x % y == 1:
                 print x
                 break

This will avoid setup and execution of the inner loop for the six out 
of seven times that x % 7 is *not* equal to zero.  This may be a 
fairly minor point when you're saving ~17,000 runs of the inner loop, 
but if your search range grows, it could be *quite* helpful.

This is a slight variant on the standard optimization method of 
lifting loop-invariants out of the loop -- in this case, the invariant 
means that the if statement will never be true.  By lifting that part 
of the if statement outside of the inner loop, we can optimize away 
the entire inner loop for certain values of x.  And while some might 
warn about the dangers of premature optimization (for it *is* 
dangerous), in this case I think it also results in a clearer, more 
easily read structure (the opposite of many optimization methods).

Jeff Shannon
Technician/Programmer
Credit International




More information about the Tutor mailing list