2016-03-31 3 views
0

Also muss ich eine rekursive Funktion namens total_len() definieren, die einen Binary String Tree nimmt und die Summe der Längen aller Blätter zurückgibt. So sollte total_len((("one", ("two","three")) , ("four","five"))) 19 zurückkehren sollte total_len(("left","right")) 9 zurück und total_len("One-leaf") sollte 8. kehre ich nicht wirklich wissen, wo ich anfangen soll, und ich weiß, dass das, was ich habe völlig falsch ist, aber was ich bisher ist dies:Python 3.4.3 .: Summe aller Längen von Strings im binären String-Baum

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 

Antwort

0

könnten Sie so etwas wie folgt aus:

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) 
Verwandte Themen