2016-03-31 50 views
0

所以我需要定義一個名爲total_len()的遞歸函數,它需要一個二進制字符串樹並返回所有樹葉長度的總和。所以total_len((("one", ("two","three")) , ("four","five")))應該返回19,total_len(("left","right"))應該返回9,並且total_len("One-leaf")應該返回8.我真的不知道從哪裏開始,我知道我擁有的是完全錯誤的,但是我到目前爲止是這樣的:Python 3.4.3 .:二進制字符串樹中所有字符串長度的總和

def total_len(BST): 
    """Takes a binary string tree and returns the sum of all the lengths of 
    of all the leaves. 

    BST->int""" 
    if isinstance(BST,tuple): 
     return total_len(len(BST[0][0])+total_len(len(BST[1][0]))) 
    else: 
     return BST 

回答

0

你可能是這樣的:

def total_len(bst): 
    if isinstance(bst, tuple): 
     if bst ==(): 
      return 0 
     else: 
      return total_len(bst[0]) + total_len(bst[1:]) 
    else: 
     return len(bst)