1、关于可视化递归问题
import turtle def tree(branchLen, t): if branchLen > 5 : t.forward(branchLen) t.right( 20 ) tree(branchLen - 15 , t) t.left( 40 ) tree(branchLen - 15 , t) t.right( 20 ) t.backward(branchLen) def main(): t = turtle.Turtle() myWin = turtle.Screen() t.left( 90 ) t.up() t.backward( 100 ) t.down() t.color( "green" ) tree( 75 , t) myWin.exitonclick() main() |
2、The Binary Search(二分法搜索)
# 正常实现 def BinarySearch(alist, item): first = 0 last = len (alist) - 1 found = False while first < = last and not found: mindpoint = (last + first) / / 2 if alist[mindpoint] = = item: found = True else : if item < alist[mindpoint]: last = mindpoint - 1 else : first = mindpoint + 1 return found # 引用递归实现 def RBinarySearch(alist, item): if len (alist) = = 0 : return False else : mindpoint = len (alist) / / 2 if alist[mindpoint] = = item: return True else : if item < alist[mindpoint]: return RBinarySearch(alist[:mindpoint], item) else : return RBinarySearch(alist[mindpoint + 1 :], item) testlist = [ 0 , 1 , 2 , 8 , 13 , 17 , 19 , 32 , 42 ] print (BinarySearch(testlist, 3 )) print (RBinarySearch(testlist, 13 )) |