Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Recursive list splitting and indexing

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading