Python Forum
nested for loops to recursion - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: nested for loops to recursion (/thread-13822.html)



nested for loops to recursion - ashkea26 - Nov-02-2018

Any advice on how to convert nested for loops to recursion. I'm kinda having trouble since I'm still a beginner.

The loops are for finding all the possible words in a Boggle game (Twisted Word search).


RE: nested for loops to recursion - Larz60+ - Nov-02-2018

here's some sample recursive code, it's a method I use to display the contents of nested dictionaries
In this code, level is use to determine indentation level. line 32 calculates level * 4 spaces to determine how to indent
line 33 checks to see if value is a dictionary itself, and if so re curses using value as the dictionary
In this way, the dictionary tree can be walked.
food = {
    'Fruits and Fruit Juices': {
        'Acerola, (west indian cherry), raw': {
            'Nutrients': {
                'water': {
                    'unit': 'g',
                    'qty': '91.41'
                },
                'energy': {
                    'unit': 'kcal',
                    'qty': '32'
                }
            }
        },
    },
    'Figs, raw': {
        'Nutrients': {
            'water': {
                'unit': 'g',
                'qty': '91.41'
            },
            'energy': {
                'unit': 'kcal',
                'qty': '32'
            }
        }
    }
}

def display_dict(thedict, level=0):
    for key, value in thedict.items():
        sp = ' ' * (4 * level)
        if isinstance(value, dict):
            print(f'{sp}{key}:')
            level += 1
            display_dict(value, level)
        else:
            print(f'{sp}{key}: {value}')
            level -= 1

if __name__ == '__main__':
    display_dict(food)
results:
Output:
Fruits and Fruit Juices: Acerola, (west indian cherry), raw: Nutrients: water: unit: g qty: 91.41 energy: unit: kcal qty: 32 Figs, raw: Nutrients: water: unit: g qty: 91.41 energy: unit: kcal qty: 32