我编写了以下代码来递归拆分列表。它首先递归地分割左侧,直到并除非剩下一个元素。
代码:
def split(class_names):
while len(class_names)>1:
n=len(class_names)
mid=n//2
left=class_names[:mid]
right=class_names[mid:]
splits.append([left,right])
class_names=left
index=1
split(left)
class_names=right
return splits
class_names=[1,2,3,4,5,6,7,8,9,10]
splits=[]
splits=split(class_names)
for ii in splits:
print(ii)
输出:
[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]
[[1, 2], [3, 4, 5]]
[[1], [2]]
[[3], [4, 5]]
[[4], [5]]
[[6, 7], [8, 9, 10]]
[[6], [7]]
[[8], [9, 10]]
[[9], [10]]
问题:
我需要一棵树及其索引的形式。左侧应在末尾加0,右侧应在末尾加1。
例如:
[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]
/\
0 / \ 1
[[1, 2], [3, 4, 5]] [[6, 7], [8, 9, 10]]
/\
0 / \ 1
[[1], [2]] [[3], [4, 5]]
Then the output should be like:
[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]] = 0
[[1, 2], [3, 4, 5]] = 00
[[6, 7], [8, 9, 10]] = 01
[[1], [2]] = 000