Python 3.4.3.: 二叉串树中所有串的长度之和
Python 3.4.3.: sum of all the lengths of strings in binary string tree
所以我需要定义一个名为 total_len()
的递归函数,它接受二叉字符串树和 return 所有叶子长度的总和。所以 total_len( ( ("one", ("two","three")) , ("four","five") ) )
应该 return 19,total_len( ("left","right") )
应该 return 9,total_len("One-leaf")
应该 return 8。我真的不知道从哪里开始,我知道我所拥有的是完全错误的,但到目前为止我所拥有的是:
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
你可以这样:
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)
所以我需要定义一个名为 total_len()
的递归函数,它接受二叉字符串树和 return 所有叶子长度的总和。所以 total_len( ( ("one", ("two","three")) , ("four","five") ) )
应该 return 19,total_len( ("left","right") )
应该 return 9,total_len("One-leaf")
应该 return 8。我真的不知道从哪里开始,我知道我所拥有的是完全错误的,但到目前为止我所拥有的是:
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
你可以这样:
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)