简体   繁体   中英

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)

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM