繁体   English   中英

解析“有序”列表并找到相应的总和和加数的算法?

[英]Algorithm to parse an "ordered" List and find respective sums and addends?

抱歉,如果之前有人问过这个问题,但我已经搜索了几天,但没有找到与我的问题有关的帮助。

我正在尝试研究的是一种解析列表(类似于预算表)并将索引分配给父母或孩子的方法。 父项是其子项的总和,子项是该父项的加数(或没有父项的数字)。

例如: [1,2,3,6] ,其中 6 是 1、2 和 3 的父级。

或更复杂的例子: [1,2,3,6,1,4,3,8,14,3,2,3,8,1,4,3,8,16,30] ,

30 是这个列表的“根”,因为 30 = 14 + 16, 14 = 6 + 8, 6 = 1 + 2 + 3 等等。这个列表总是有点顺序的,也就是说孩子们总是一起出现在他们的父母之前(当然,父母是另一个父母的孩子时除外)。 我试图找到最有效的方法,我的 2 个解决方案使用堆栈,但它们不是 100% 正确,因为上面的 2 个示例失败了。 这是两者的伪代码:

解决方案尝试 1

stack = []
for number in list
    if stack.isEmpty()
        stack.push(number)
    elif stack.peek() > number
        stack.push(number)
    else
        copy = stack
        temp = []
        current = number
        while current > 0
            popped = copy.pop()
            temp.push(popped)
            current -= popped
        if current == 0
            while temp
                child = temp.pop()
                child.parent = number
            stack = copy
    stack.push(number)

解决方案尝试2

stack = []
for number in list
    stack.push(number)

while stack.size() > 1
    child = stack.pop()
    copy = stack
    temp = []
    if child > stack.peek()
        while current > 0 and copy.size() > 0
            popped = copy.pop()
            temp.push(popped)
            current -= popped    
        if current == 0
            while temp
                child = temp.pop()
                child.parent = number

任何想法或想法将不胜感激。 在这一点上,我正在用头撞墙。

编辑

复杂示例解决方案[1,2,3,6,1,4,3,8,14,3,2,3,8,1,4,3,8,16,30]

                   30
            /             \
      14                     16
    /      \              /        \
  6          8           8             8
/  |  \   /  |  \     /  |   \     /   |   \
1  2   3  1  4   3   3   2    3   1    4    3

这是一个有趣的问题。 这是使用列表作为树的递归解决方案(索引 0 处的根,以下索引处的子项):

def get_tree(nums, trees=None):
    trees = trees or []
    if not nums:
        return trees[0] if len(trees) == 1 else None
    val, *nums = nums
    for i in range(len(trees)):
        if val == sum(c[0] for c in trees[i:]):
            result = get_tree(nums,  trees[:i] + [[val] + trees[i:]])
            if result:
                return result
    return get_tree(nums, trees + [[val]])

print(get_tree([1, 2, 3, 6]))
print(get_tree([1, 2, 3, 6, 1, 4, 3, 8, 14, 3, 2, 3, 8, 1, 4, 3, 8, 16, 30]))
print(get_tree([1, 2, 3, 7]))
print(get_tree([1, 2, 3]))

# [6, [1], [2], [3]]
# [30, [14, [6, [1], [2], [3]], [8, [1], [4], [3]]], [16, [8, [3], [2], [3]], [8, [1], [4], [3]]]]
# None
# [3, [1], [2]]

get_tree的逻辑如下:

  • 您在迭代数字列表时收集树列表
  • nums每个位置,您可以执行以下两项操作之一:
    • 取树列表末尾的树的任何后缀( trees[i:] ),并将它们作为子树放在以当前编号为根的新树下
    • 将当前数字作为新树添加到堆栈中
  • 当您到达列表末尾并且堆栈中只有一棵树时,这就是结果

您基本上会得到一个后序遍历并从中生成所有可能的树,并在此过程中淘汰那些总和不匹配的树。 对于正整数,这个过程是确定性的,即只有一棵有效树或没有。 对于非正整数,可能有多个可能的有效树。 一个简单的例子是一个只有零的列表,其中任何树都是有效的。

另一种解决方案:

如果您的输入按问题所述排序,您可以利用sorted()函数和递归。

示例(假设非空输入):

def _get_tree(lst):   
    new_children, cnt = [], 0
    for idx, v in sorted(enumerate(lst[:-1]), key=lambda k: k[1], reverse=True):
        cnt += v
        new_children.append((idx, v))

        if cnt == lst[-1]:
            start, new_children = 0, sorted(new_children, key=lambda k: k[0])
            for idx2, v2 in new_children:
                if idx2 - start == 0:
                    yield lst[start]
                else:
                    yield [v2, [*_get_tree(lst[start:idx2+1])]]
                start = idx2 + 1
            break

def get_tree(lst):
    return list([lst[-1], [*_get_tree(lst)]])

print(get_tree([1,2,3,6,1,4,3,8,14,3,2,3,8,1,4,3,8,16,30]))
print(get_tree([1, 2, 3]))
print(get_tree([1, 2, 3, 6]))
print(get_tree([1, 2, 3, 7]))

印刷:

[30, [[14, [[6, [1, 2, 3]], [8, [1, 4, 3]]]], [16, [[8, [3, 2, 3]], [8, [1, 4, 3]]]]]]
[3, [1, 2]]
[6, [1, 2, 3]]
[7, []]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM