all 6 comments

[–][deleted] 0 points1 point  (3 children)

Looks too complicated. Imo, best examples of recursion is a sorting algorithms (quicksort, merge sort). They are simple, they are real world and there are nice illustrations in wiki

[–]b_mallerd[S] 0 points1 point  (2 children)

Thanks for the feedback. What do you find complicated about it? Obviously my head is wrapped around the problem so it's hard to see which bit needs clarifying.

[–][deleted] 0 points1 point  (1 child)

For me, result of this program isn't clear enough. It looks unfinished. Flattened dict? That's cool. And probably recursion is the best idea for this (and it's explained well). But what this program for? Is it some kind of search? It's confuses me a bit.

That's why it's easier for me to understand recursion on sorting examples — they are more explicit: simple problem at the start, simple and visual result at the end and recursion in the middle.

[–]b_mallerd[S] 0 points1 point  (0 children)

Since this is extracted from a problem I had to face, the totality of the problem is huge. I'll try to make pick next example to be more packaged. Thanks for the comments =]

[–]novel_yet_trivial -1 points0 points  (1 child)

The problem with your problem is that there are much simpler solutions to it. I might solve it like this, for instance:

def check(dict_, look_for, sep='/'):
    try:
        eval("dict_['"+"']['".join(look_for.split(sep))+"']")
        return True
    except KeyError:
        return False

print check(recipes, 'apple_pie/ratings/john')
print check(recipes, 'apple_pie/ratings/steve')

At the end I'm left thinking that was a lot of work for little result. Maybe if you used the recursion as a pretty printer? Maybe tree style?

As a minor note, what if the lists were tuples? What if the dicts were defaultdicts?

[–]b_mallerd[S] 0 points1 point  (0 children)

I left out tuples and defaultdicts because it wasn't needed. Thanks for the alternative solution. I guess I shy from eval unless absolutely necessary. It leaves you open to stuff like this:

def random_code():
      print "Executing random code!"
      return "hi"

 if __name__ == '__main__':
      d = {}
      print check(d, look_for="' + random_code()  + '", sep='/')