【问题标题】:How do I test a sum tree?如何测试求和树?
【发布时间】:2016-01-15 11:31:39
【问题描述】:

我有 2 个列表。一个包含values,另一个包含levels,这些值保存在求和树中。 (列表长度相同)

例如:

[40,20,5,15,10,10] and [0,1,2,2,1,1]

这些列表正确对应是因为

- 40
- - 20
- - - 5
- - - 15
- - 10
- - 10

(20+10+10) == 40 and (5+15) == 20

我需要检查给定的值列表及其级别列表是否正确对应。到目前为止,我已经设法将这个函数放在一起,但由于某种原因,对于正确的列表 arraynumbers,它没有返回 True。在此处输入 numbers 将是 [40,20,5,15,10,10] 并且 array 将是 [0,1,2,2,1,1]

def testsum(array, numbers):
    k = len(array)
    target = [0]*k
    subsum = [0]*k
    for x in range(0, k):
        if target[array[x]]!=subsum[array[x]]:
            return False
        target[array[x]]=numbers[x]
        subsum[array[x]]=0
        if array[x]>0:
            subsum[array[x]-1]+=numbers[x]
    for x in range(0, k):
        if(target[x]!=subsum[x]):
            print(x, target[x],subsum[x])
            return False
    return True

【问题讨论】:

  • 您可以从列表中间开始进行比较,我认为这将是一种更有趣的方法
  • 这将如何运作?
  • 你不能只创建一棵树然后在遍历树时检查总和吗?
  • 我正在尝试这样做。
  • @user3050748:你能给我另一棵树吗? IE。根据父母的一些祖先。我已经做了这棵树。所以我需要另一棵树进行测试

标签: python list for-loop


【解决方案1】:

我使用itertools.takewhile 运行此程序以获取每个级别下的子树。将其放入递归函数中并断言所有递归都通过。

我通过获取next_vnext_l 并尽早测试以查看当前节点是否是父节点并仅在需要构建时才构建subtree,从而稍微改进了我的初始实现。这种不等式检查比遍历整个vs_ls zip 要便宜得多。

import itertools

def testtree(values, levels):
    if len(values) == 1:
        # Last element, always true!
        return True
    vs_ls = zip(values, levels)
    test_v, test_l = next(vs_ls)
    next_v, next_l = next(vs_ls)
    if next_l > test_l:
        subtree = [v for v,l in itertools.takewhile(
            lambda v_l: v_l[1] > test_l,
            itertools.chain([(next_v, next_l)], vs_ls))
                   if l == test_l+1]
        if sum(subtree) != test_v and subtree:
            #TODO test if you can remove the "and subtree" check now!
            print("{} != {}".format(subtree, test_v))
            return False
    return testtree(values[1:], levels[1:])

if __name__ == "__main__":
    vs = [40, 20, 15, 5, 10, 10]
    ls = [0, 1, 2, 2, 1, 1]
    assert testtree(vs, ls) == True

不幸的是,它给代码增加了很多复杂性,因为它提取了我们需要的第一个值,这需要额外的 itertools.chain 调用。这并不理想。除非您期望获得非常大的 valueslevels 列表,否则可能值得做 vs_ls = list(zip(values, levels)) 并按列表而不是迭代器来处理。比如……

...
vs_ls = list(zip(values, levels))
test_v, test_l = vs_ls[0]
next_v, next_l = vs_ls[1]
...

    subtree = [v for v,l in itertools.takewhile(
        lambda v_l: v_l[1] > test_l,
        vs_ls[1:]) if l == test_l+1]

我仍然认为最快的方法可能是使用几乎类似于状态机的方法迭代一次并获取所有可能的子树,然后单独检查它们。比如:

from collections import namedtuple

Tree = namedtuple("Tree", ["level_num", "parent", "children"])
# equivalent to
# # class Tree:
# #     def __init__(self, level_num: int,
# #                        parent: int,
# #                        children: list):
# #         self.level_num = level_num
# #         self.parent = parent
# #         self.children = children

def build_trees(values, levels):
    trees = []  # list of Trees
    pending_trees = []
    vs_ls = zip(values, levels)
    last_v, last_l = next(vs_ls)
    test_l = last_l + 1
    for v, l in zip(values, levels):
        if l > last_l:
            # we've found a new tree
            if l != last_l + 1:
                # What do you do if you get levels like [0, 1, 3]??
                raise ValueError("Improper leveling: {}".format(levels))
            test_l = l

            # Stash the old tree and start a new one.
            pending_trees.append(cur_tree)
            cur_tree = Tree(level_num=last_l, parent=last_v, children=[])

        elif l < test_l:
            # tree is finished

            # Store the finished tree and grab the last one we stashed.
            trees.append(cur_tree)
            try:
                cur_tree = pending_trees.pop()
            except IndexError:
                # No trees pending?? That's weird....
                # I can't think of any case that this should happen, so maybe
                # we should be raising ValueError here, but I'm not sure either
                cur_tree = Tree(level_num=-1, parent=-1, children=[])

        elif l == test_l:
            # This is a child value in our current tree
            cur_tree.children.append(v)
    # Close the pending trees
    trees.extend(pending_trees)
    return trees

这应该为您提供Tree 对象的列表,每个对象都具有以下属性

level_num  := level number of parent (as found in levels)
parent     := number representing the expected sum of the tree
children   := list containing all the children in that level

完成后,您应该可以简单地检查

all([sum(t.children) == t.parent for t in trees])

但请注意,我无法测试第二种方法。

【讨论】:

  • @user3050748 我对第一种方法进行了一些改进,下面应该是一种更省时的方法(尽管尚未经过测试)。有什么不懂的地方告诉我
  • 如果我尝试调用你的第二种方法,它会在trees.append(cur_tree) 行给我一个错误:local variable 'cur_tree' is referenced before assignment
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-03
  • 2010-11-20
相关资源
最近更新 更多