递归清单分裂和索引
我已经编写了以下代码以递归分配列表。它首先将左侧的左侧分开,直到并剩下一个元素。
代码:
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
I have written the following code to split the list recursively. It first splits the left hand side recursively until and unless one,one element is left.
Code:
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)
Output:
[[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]]
Problem:
I need this in the form of a tree and its index. Left side should add 0 to the end and right should add 1 at the end.
For example:
[[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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的递归已经下降,但是当您左右横穿索引时,需要跟踪索引。这是一种具有附加参数的方法,并重新编写为生成器:
输出:
You've got the recursion down, but need to track the index as you traverse left and right. Here's a way with an additional parameter, and re-written as a generator:
Output: