【问题标题】:Python 3.4.3.: sum of all the lengths of strings in binary string treePython 3.4.3.:二进制字符串树中所有字符串长度的总和
【发布时间】:2016-03-31 18:57:02
【问题描述】:

所以我需要定义一个名为total_len() 的递归函数,它接受一个二进制字符串树并返回所有叶子的长度之和。所以total_len( ( ("one", ("two","three")) , ("four","five") ) ) 应该返回 19,total_len( ("left","right") ) 应该返回 9,total_len("One-leaf") 应该返回 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

【问题讨论】:

    标签: python recursion binary-tree string-length


    【解决方案1】:

    你可以这样:

    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)
    

    【讨论】:

      猜你喜欢
      • 2011-12-04
      • 2015-11-21
      • 1970-01-01
      • 2021-11-09
      • 2019-05-11
      • 2012-09-11
      • 2019-12-08
      • 1970-01-01
      • 2016-05-24
      相关资源
      最近更新 更多