Clarity vs. code reuse/generality

pdpi pdpinheiro at gmail.com
Tue Jul 7 14:31:39 EDT 2009


On Jul 7, 7:06 pm, Paul Rubin <http://phr...@NOSPAM.invalid> wrote:
> pdpi <pdpinhe... at gmail.com> writes:
> > Personally, I think the code is an unreadable mess, but that's mostly
> > because of all the micro optimizations, not the generality of it.
> > Here's my unoptimized, but still equally generic, version:
>
> That version doesn't use "sense" inside the binary search, i.e. it
> relies on the function being monotonically increasing.

You're right, make that:

def _binary_search(lo, hi, func, target, epsilon):
    sense = cmp(func(hi), func(lo))
    if sense == 0:
        return None
    guess = (lo + hi) / 2.
    while abs(func(guess) - target) > epsilon:
        guess = (lo + hi) / 2.
        if sense * func(guess) > target:
            hi = guess
        elif sense * func(guess) < target:
            lo = guess
        elif lo == hi:
            return None
    return guess

Seems I had a serious brain cramp while posting that...



More information about the Python-list mailing list