【问题标题】:For each node in tree, add underscores to each node so that all children are covered对于树中的每个节点,为每个节点添加下划线,以便覆盖所有子节点
【发布时间】:2019-11-15 00:26:32
【问题描述】:

我正在尝试编写一个函数,它接受一棵树,并返回一棵新树,其中每个节点都覆盖了它的所有子节点并在其周围有括号。

这是我目前的功能。由于递归,我发现很难跟踪正在发生的事情,即使在玩了一段时间之后,查明问题仍然具有挑战性。

 def covered_tree(node):
  parent, children = node
  new_node = None
  for childs in children:
    cover_len = 0
    for each_child in childs:
      covered_tree(childs)
      cover_len += len(each_child)
    cover_len -= len(parent)-2
    parent = '['+parent+'_'*cover_len+']'
    new_node = (parent, children)
  return new_node

对于输入,

("hello", (("a", ()), ("b", (("cde", ()), ("fg", ())))))

预期输出,

('[hello_____]', (('[a]', ()), ('[b______]', (('[cde]', ()), ('[fg]', ())))))

b 后跟 6 个下划线,因为 len('[cde]'+'[fg]')-2-len('a') 是 6,减二是外括号。

【问题讨论】:

  • 为什么hello后面要跟5个下划线和b - 6?澄清你的逻辑
  • @RomanPerekhrest 我已经澄清了这个问题。同样的逻辑适用于hello,len('[a]'+'[b______]')-2-len('hello') 等于5。希望更好

标签: python recursion tree tuples


【解决方案1】:

你可以使用递归:

def cover_tree(d):
   c = tuple(map(cover_tree, d[1]))
   return ('['+d[0]+']'+('_'*(sum(len(j) for j, _ in c) - 2 - len(d[0]))), c)

tree = ("hello", (("a", ()), ("b", (("cde", ()), ("fg", ())))))
print(cover_tree(tree))

输出:

('[hello]_____', (('[a]', ()), ('[b]______', (('[cde]', ()), ('[fg]', ())))))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多