EDIT: Below is the recommended answer and how it is still not quite right.
There are many similar questions in Qaru, but none of them are similar to Python. I'm starting to program, so please come through.
I have a tree of nested dictionaries, for example:
[{'word': 'The', 'next': [{'word': 'End', 'next': None}, {'word': 'quick', 'next': [{'word': 'brown', 'next': [{'word': 'fox', 'next': None}]}]}, {'word': 'best', 'next': [{'word': 'of', 'next': [{'word': 'times', 'next': None}]}]}]}]
I want to smooth all the paths from top to bottom and in the end:
[[{'word': 'The'}, {'word': 'End'}], [{'word': 'The'}, {'word': 'quick'}, {'word': 'brown'}, {'word': 'fox'}], [{'word': 'The'}, {'word': 'best'}, {'word': 'of'}, {'word': 'times'}]]
I made a small recursive function that initially created the original structure, but it's hard for me to overdo it. This, as I understand it:
def flatten_combinations(result_tree, current_combo = None, all_combos = None): if current_combo is None: current_combo = [] if all_combos is None: all_combos = [] if result_tree is None: all_combos.append(current_combo) return for word in result_tree: current_combo.append({'word': word['word']}) flatten_combinations(word['next'], current_combo, all_combos) return current_combo
... which returns this:
[{'word': 'The'}, {'word': 'End'}, {'word': 'quick'}, {'word': 'brown'}, {'word': 'fox'}, {'word': 'best'}, {'word': 'of'}, {'word': 'times'}]
... which is clearly somewhat close, but not quite right.
I know that the function is probably terribly non-neat, but I teach myself programming, so Iām not even trying to use possibly existing language functions that would allow me to overcome thoughts through this material from scratch ("he said, sending Q & A to the site A in the hope that his members will help him figure it out a bit. "
So: what am I doing wrong?
EDIT : Moshe below fixed a couple of problems:
def flatten_combinations(result_tree, current_combo = None, all_combos = None): if current_combo is None: current_combo = [] if all_combos is None: all_combos = [] if result_tree is None: all_combos.append(current_combo) return for word in result_tree: current_combo = current_combo[:] current_combo.append({'word': word['word']}) flatten_combinations(word['next'], current_combo, all_combos) return all_combos
This is even closer, but not entirely correct:
[{'word': 'The'}, {'word': 'End'}], [{'word': 'The'}, {'word': 'End'}, {'word': 'quick'}, {'word': 'brown'}, {'word': 'fox'}], [{'word': 'The'}, {'word': 'End'}, {'word': 'quick'}, {'word': 'best'}, {'word': 'of'}, {'word': 'times'}]]