[Tutor] Binary chop function - this works, but I'm not sure why

Arun Srinivasan soulguidedtelescope at gmail.com
Thu Feb 14 01:49:47 CET 2008

I'm trying to learn Python, and I decided to try kata 2 </> from the
CodeKate website. It's basically just a challenge to implement a binary
search in different ways.

I wrote an implementation that works, but I'm confused as to why.

def chop(search_int, sorted_list):
    if len(sorted_list) == 1 or 2:
        for x in sorted_list:
            if x == search_int:
                return sorted_list.index(x)
        return -1

    midpoint = (len(sorted_list) - 1) / 2
    mp_value = sorted_list[midpoint]

    if mp_value == search_int:
        return midpoint
    elif mp_value > search_int:
        return chop(search_int, sorted_list[:midpoint])
        return chop(search_int, sorted_list[midpoint + 1:])

Basically, it only returns the index if it matches in the if statement at
the beginning of the function, but since that is limited to lists of length
2 or 1, why doesn't it return only 0 or 1 as the index? I think there is
something about recursion here that I'm not fully comprehending.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080213/1844543f/attachment.htm 

More information about the Tutor mailing list