1

I've implemented the exact same functionality with recursions, I also want a version without recursion as Python has a recursion limit and there are problems while sharing data.

sublist2 = [{'nothing': "Notice This"}]
sublist1 = [{'include':[sublist2]}]

mainlist = [{'nothing': 1}, {'include':[sublist1, sublist2]},
            {'nothing': 2}, {'include':[sublist2]}]

What is to be filled in the Todo?

for i in mainlist:
    if 'nothing' in i:
         # Do nothing
    else if 'include' in i:
         # Todo
         # Append the contents of the list mentioned recursively
         # in it's own place without disrupting the flow

After the operation the expected result

mainlist = [{'nothing': 1}, 
            {'nothing': "Notice This"}, {'nothing': "Notice This"}, 
            {'nothing':2}, 
            {'nothing': "Notice This"}]

If you notice sublist1 references to sublist2. That's the reason

{'include':[sublist1, sublist2]} is replaced by

{'nothing':"Notice This"}, {'nothing':"Notice This"}

I've tried the following

Inserting values into specific locations in a list in Python

How to get item's position in a list?

Community
  • 1
  • 1
Abhirath Mahipal
  • 938
  • 1
  • 10
  • 21
  • 1
    I am confused. Do you want to do this recursively or not? Your first paragraph and title contradict eachother. – Jokab Jul 13 '16 at 09:40
  • You're correct that Python has recursion limits (defaulting to 1000), but if your data structure is breaking that, then I'd say there's something seriously wrong with your data. – Jon Clements Jul 13 '16 at 09:43
  • @Jokab I meant the list should populate recursively. I don't want to use recursions. Will correct it – Abhirath Mahipal Jul 13 '16 at 10:01
  • @JonClements There are problems with data sharing and speed. I've replicated it to a smaller scale to explain it better. – Abhirath Mahipal Jul 13 '16 at 10:04

1 Answers1

2

Instead of using recursion, you just look at the nth element and change it in place until it doesn't need any further processing.

sublist2 = [{'nothing': "Notice This"}]
sublist1 = [{'include':[sublist2]}]

mainlist = [{'nothing': 1}, {'include':[sublist1, sublist2]},
            {'nothing': 2}, {'include':[sublist2]}]

index = 0
while index < len(mainlist):
    if 'nothing' in mainlist[index]:
        index += 1
    elif 'include' in mainlist[index]:
        # replace the 'include' entries with their corresponding list
        mainlist[index:index+1] = mainlist[index]['include']
    elif isinstance(mainlist[index], list):
        # if an entry is a list, replace it with its entries
        mainlist[index:index+1] = mainlist[index]

Note the difference between assigning to an entry l[0] and assigning to a slice l[0:1]

>>> l = [1, 2, 3, 4]
>>> l[3] = ['a', 'b', 'c']
>>> l
[1, 2, 3, ['a', 'b', 'c']]
>>> l[0:1] = ['x', 'y', 'z']
>>> l
>>> ['x', 'y', 'z', 2, 3, ['a', 'b', 'c']]
Daniel Hepper
  • 28,981
  • 10
  • 72
  • 75