python - Binary search implementations -
i'm stuck in implementing 5 different ways of binary chop ( task http://codekata.com/kata/kata02-karate-chop/ ). may give ideas more approaches?
that's have got:
1)
def left_chop(key, arr): l = 0 r = len(arr) while l<r: m = (l+r)/2 if key<=arr[m]: r = m else: l = m+1 return l if key == arr[l] else -1
2)
def left_chop(key, array, left = 0, right = none): if right == none: right = len(array) if left==right: return left if key == array[left] else -1 m = (left+right)/2 if key<=array[m]: return left_chop(key, array, left, m) else: return left_chop(key, array, m+1, right)
3)i know, it's similar first
class find(object): def __init__(self, key, array): self.array = array self.key = key self.l = 0 self.r = len(array) def left_chop(self): while self.l<self.r: self.step() return self.l if self.key == self.array[self.l] else -1 def step(self): m = (self.l+self.r)/2 if self.key<=self.array[m]: self.r = m else: self.l = m+1
i had tried come in functional programming style, haven't succeeded.
you use generator:
def chopper(array, val): edges = (0, len(array)) while true: m = sum(edges)/2 edges = (edges[0], m) if array[m] >= val else (m+1, edges[1]) yield edges def chopsearch(array, val): l, r in chopper(array, val): if array[l] == val: return l if l==r: return -1
Comments
Post a Comment