代码之家  ›  专栏  ›  技术社区  ›  Ash

递归列表拆分和索引

  •  0
  • Ash  · 技术社区  · 2 年前

    我编写了以下代码来递归拆分列表。它首先递归地分割左侧,直到并除非剩下一个元素。

    代码:

    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
    
    1 回复  |  直到 2 年前
        1
  •  1
  •   Mark Tolonen    2 年前

    您已经完成了递归,但需要在向左和向右遍历时跟踪索引。这是一种带有附加参数的方法,并重新编写为生成器:

    def split(class_names, index='0'):
        if (n := len(class_names)) < 2:
            return
        mid = n // 2
        left, right = class_names[:mid], class_names[mid:]
        yield [left, right], index
        yield from split(left, index + '0')
        yield from split(right, index + '1')
    
    class_names = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    for node, index in split(class_names):
        print(f'{node} = {index}')
    

    输出:

    [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]] = 0
    [[1, 2], [3, 4, 5]] = 00
    [[1], [2]] = 000
    [[3], [4, 5]] = 001
    [[4], [5]] = 0011
    [[6, 7], [8, 9, 10]] = 01
    [[6], [7]] = 010
    [[8], [9, 10]] = 011
    [[9], [10]] = 0111