Full story

Posted on 05-08-2008 under Python

The second way I’ll implement binary search for Kata Two — Karate Chop will be with recursion. I haven’t used recursion much in my day-to-day work, but I’ve never thought of it as a particularly hard concept to grasp, it just seems that the problems I work aren’t optimally solved with it. The most interesting part of recursion is finding the condition that ends it. Here’s my solutions:

def chopTwo(value, list):
upper = len(list) - 1
lower = 0

return chopTwoRec(upper, lower, value, list)

def chopTwoRec(upper, lower, value, list):
index = (upper + lower) / 2

if index < 0 or upper < lower:
return -1
elif list[index] == value:
return index
elif value > list[index]:
lower = index + 1
elif value < list[index]:
upper = index - 1

return typeTwoRec(upper, lower, value, list)

No comment yet

Don't be shy, express yourself ! ;)

Post your comments

Fill up the fields below. Email is required but won't be revealed to anyone. Some (simple) html is allowed. If you want to cite another comment use the "Quote" link located beside each author. Finally be nice or at least keep it polite. Thanks for posting.