代码示例:
def count_superiors(lst, index):
count = 0
while index != -1:
count += 1
index = lst[index]
return count
def count_all_superiors(lst):
return [count_superiors(lst, i) for i in range(len(lst))]
# 示例
lst = [-1, 0, 1, 2, 1, 2]
print(count_all_superiors(lst))
# 输出 [0, 1, 2, 3, 2, 3]
该解决方法通过编写两个函数,分别计算给定列表中每个元素的上级数量以及整个列表中所有元素的上级数量。其中,count_superiors 函数计算单个元素的上级数量,需要给定列表和元素索引;count_all_superiors 函数则调用 count_superiors 函数,遍历整个列表,返回所有元素的上级数量列表。
代码示例中给出了一个示例列表 lst,其上级关系为:
-1
└── 0
└── 1
├── 2
└── 4
└── 3
└── 2
列表中有一个根元素 -1,其余元素都是它的下级。例如,元素 0 的上级是 -1,元素 1 的上级是 0,元素 2 的上级是 1,元素 3 的上级是 2,元素 4 的上级是 1,而 -1 没有上级。在这个例子中,count_all_superiors 函数返回的上级数量列表分别为 0、1、2、3、2、3。