Saad
Saad

Reputation: 1360

recursion in Python dictionary

I am implementing a switch/case expression through dictionary in Python. Can anyone tell me why the following recursive call is wrong?

I am getting an exception: RuntimeError: maximum recursion depth exceeded

def rec(x):
    return {
        'a': 'one',
        'b': 'two',
        'ac': rec('a'),
    }.get(x,x)

Upvotes: 0

Views: 162

Answers (2)

Mike Graham
Mike Graham

Reputation: 76793

Your dict values are not put in lazily, which means it always creates the dict

{
    'a': 'one',
    'b': 'two',
    'ac': rec('a'),
}

whether you look up 'ac' or not. As such, you can't just look up 'a' in your recursive call -- you have to make the dict (recursing another layer) first.

You'll have to write this code another way.

Upvotes: 0

Blckknght
Blckknght

Reputation: 104852

The reason you're getting infinite recursion is because you're telling Python to store the result of the recursive call rec('a') in the dictionary. This means it recurses unconditionally, since you always build the dictionary before doing the lookup.

One way to solve this would be to store lambda functions in the dictionary, and then only call the one you get. In this version, the recursive call is only made when the appropriate x value is passed in:

def rec(x):
    return {
        'a': lambda: 'one',
        'b': lambda: 'two',
        'ac': lambda: rec('a'),
    }.get(x, lambda: x)()

Unfortunately, that's a bit cumbersome. I'm not sure I'd bother if there were just have three cases and a default. I'd just use a series of if statements, even though that might not be as efficient as a dictionary lookup.

Upvotes: 3

Related Questions