Clarity vs. code reuse/generality

pdpi pdpinheiro at gmail.com
Wed Jul 8 10:06:09 EDT 2009


On Jul 8, 2:24 am, Paul Rubin <http://phr...@NOSPAM.invalid> wrote:
> pdpi <pdpinhe... at gmail.com> writes:
> >     while abs(func(guess) - target) > epsilon:
> >         guess = (lo + hi) / 2.
> >         if sense * func(guess) > sense * target:
> >             hi = guess
> >         elif sense * func(guess) < sense * target:
> >             lo = guess
> >         elif lo == hi:
> >             return None
> >     return guess
>
> That is completely confusing.  I get the, er, impression that "sense"
> is supposed to change during the loop, and it takes much head
> scratching to tell whether what you have there is right or not.  Also,
> it calls func 3 times on each loop, which could be extremely slow.
> You don't know what func does, so eliminating 2/3 of the calls to it
> is not a micro-optimization--it could be a major time saving.
>
> Yet another version:
>
>     def _binary_search(x0, x1, func, target, epsilon):
>         y0,y1 = func(x0), func(x1)
>         while abs(y1 - target) > epsilon:
>             if x0 == x1 or cmp(y0,target) == cmp(y1,target):
>                 return None
>             xn = (x0 + x1) / 2.
>             yn = func(xn)
>             if cmp(yn,target) == cmp(y0,target):
>                x0,y0 = xn,yn
>             else:
>                x1,y1 = xn,yn
>         return x1

micro-optimization was perhaps too harsh, but it is an optimization
that's not obvious for the newbie, and one best learnt from experience
rather than having it spoon fed. I'll restate: you should start with
the cleanest code possible and mangle it for performance. Then again,
that implicitly assumes that f(x) is more readable than y, which is
really a matter of taste...



More information about the Python-list mailing list