I need figuring out how to create (what I think needs to be) a recursive function. My brain has never coped well with recursion.
I have a flat collection of items, that needs to be turned into a nested collection based on a value in each item. Each item has, among other attributes, a type. One possible item.type is "group header". Each "group header" will be closed by a "group footer". I need to nest the collection based on those two types.
The collection might look like this:
- item 1: type = blurb
- item 2: type = group header
- item 3: type = question
- item 4: type = question
- item 5: type = group header
- item 6: type = question
- item 7: type = question
- item 8: type = group footer
- item 9: type = question
- item 10: type = group footer
I want to make that collection look more like this:
- item 1: blurb
- item 2: header, item 10: footer
- item 3: question
- item 4: question
- item 5: group header, item 8: footer
- item 6: question
- item 7: question
- item 9: question
There can be any depth of nesting, hence (I think) the need for recursion.
Any pointers on how to do it greatly appreciated. I simply cannot get my head around it, and I can't find an example online where a tag (in my case, "group footer") is used to jump back up a nest level.
Here are the beginnings of a python fiddle to work with: http://pythonfiddle.com/recursion-fiddle-ninety-nine
Example data from link:
test_data = [{"id":1, "type":"blurb", "info":"This is the blurb"},
{"id":2, "type":"header", "info":"This is the first group header"},
{"id":3, "type":"question", "info":"This is the first question"},
{"id":4, "type":"question", "info":"This is the second question"},
{"id":5, "type":"header", "info":"This is the second group header"},
{"id":6, "type":"question", "info":"This is the third question"},
{"id":7, "type":"question", "info":"This is the fourth question"},
{"id":8, "type":"footer", "info":"This is the footer for the second header"},
{"id":9, "type":"question", "info":"This is the fifth question"},
{"id":10, "type":"footer", "info":"This is the footer for the first header"}]
thanks in advance
Jay