recursion in Python dictionary -


i implementing switch/case expression through dictionary in python. can tell me why following recursive call wrong?

i getting 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 because you're telling python store result of recursive call rec('a') in dictionary. means recurses unconditionally, since build dictionary before doing lookup.

one way solve store lambda functions in dictionary, , call 1 get. in version, recursive call made when appropriate x value passed in:

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

unfortunately, that's bit cumbersome. i'm not sure i'd bother if there have 3 cases , default. i'd use series of if statements, though might not efficient dictionary lookup.


Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

Rendering JButton to get the JCheckBox behavior in a JTable by using images does not update my table -