Home > database >  Recursive list splitting and indexing
Recursive list splitting and indexing

Time:06-30

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

CodePudding user response:

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:

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}')

Output:

[[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
  • Related