Home > Mobile >  Delete only first occurrence of element in list Recursively
Delete only first occurrence of element in list Recursively

Time:12-18

I am trying to remove only the first occurrence of an element from a file-like structure. I have the following code:

d2 = ("home",
       [("Documents",
         [("FP",
           ["lists.txt", "recursion.pdf", "functions.ipynb", "lists.txt"]
         )]
       ),
       "tmp.txt",
       "page.html"]
     )

def print_tree(dirtree, file_to_find):
    if type(dirtree) == str:
      if file_to_find == dirtree:
        return []
      else:  
        return [dirtree]
 
    name, subdir = dirtree
    a = []
    for subtree in subdir:
      t = print_tree(subtree, file_to_find)
      a  = t
    return (name, a)

This returns for print_tree(d2, "lists.txt"):

('home', ['Documents', ['FP', ['recursion.pdf', 'functions.ipynb']], 'tmp.txt', 'page.html'])

But I wanted it to return:

('home', ['Documents', ['FP', ['recursion.pdf', 'functions.ipynb', 'lists.txt']], 'tmp.txt', 'page.html'])

Do you have any suggestions how can I achieve this behaviour? Thanks in advance for any help you can provide.

CodePudding user response:

This is a recursive function that searches for the element in the file-like structure and removes it if it's found

def remove_first_occurrence(structure, element):
    if isinstance(structure, list):
        if element in structure:
            # Remove the first occurrence of the element
            structure.remove(element)
            return structure
        else:
            # Recursively search the sublists for the element
            for i in range(len(structure)):
                structure[i] = remove_first_occurrence(structure[i], element)
            return structure
    else:
        # If the element is not a list, it can't contain the element we're looking for
        return structure

# Test the function
d2 = ('home',
      [('Documents',
        [('FP',
          ['lists.txt', 'recursion.pdf', 'functions.ipynb', 'lists.txt']
         )]
       ),
       'tmp.txt',
       'page.html']
     )

# Convert d2 which is a tuple to a list
d2_list = list(d2)

modified_list = remove_first_occurrence(d2_list, 'lists.txt')

# Convert the modified list back to a tuple
modified_tuple = tuple(modified_list)
print(modified_tuple)

Output:

('home', ['Documents', ['FP', ['recursion.pdf', 'functions.ipynb', 'lists.txt']], 'tmp.txt', 'page.html'])
  • Related