Simple Search


In [ ]:
def search(x, nums):
    try:
        return nums.index(x)
    except:
        return -1

#See it in action!    
checklist = [3, 9, 6, 2, 10, 30, 18, 7, 8]
print search(9, checklist)

Linear Search


In [ ]:
def search(x, nums):
    for i in range(len(nums)):
        if nums[i] == x:
            return i       # found! return index
    return -1


#See it in action!
checklist = [3,9,6, 2, 10, 30, 18, 7, 8]
print search(9, checklist)

Binary Search (Non-Recursive)


In [ ]:
def search(x, nums):
    low = 0
    high = len(nums) - 1
    while low <= high:       # Still more to search
        mid = (low + high)/2 # Position of middle item
        item = nums[mid]
        if x == item:        # Found it! Return the index
            return mid
        elif x < item:       # x is in lower half of range
            high = mid - 1   #  move top marker down
        else:                # x is in upper half of range
            low = mid + 1    #  move bottom marker up
    return -1


## See it in action!
##NB:  Don't forget that the list must be SORTED
checklist = [3,9,6, 2, 10, 30, 18, 7, 8]
checklist.sort()
print checklist
print search(9, checklist)

Recursive Definitions

Example: Factorial


In [ ]:
def fact(n):
    if n == 0:
         return 1
    else:
         return n* fact(n-1)

print fact(4)

Example: String Reversal


In [ ]:
def reverse(s):
    if s == "":
        return s
    else:
         return reverse(s[1:])+s[0]
        
print reverse("hello")
print reverse("evian")
print reverse("toohottohoot")
print reverse("tacocat")

Binary Search (Recursive)


In [ ]:
def recBinSearch(x, nums, low, high):
    #### must be ordered!  Don't forget!######

    if low > high:  # No more to look, return -1
        return -1
    mid = (low + high)/2
    item = nums[mid]
    if item == x:
        return mid      #returns INDEX of the number
    elif x < item:          # Look in lower half
        return recBinSearch(x, nums, low, mid-1)
    else:                   # Look in upper half
        return recBinSearch(x, nums, mid+1, high)


def search(x, nums):
    return recBinSearch(x, nums, 0, len(nums)-1)

checklist = [3,9,6, 2, 10, 30, 18, 7, 8]
checklist.sort()
print checklist
print search(9, checklist)