1

Enhancing this question, I got:

def pretty(d, steps = -1, indent = 0):
    for key, value in d.iteritems():
        c = 0
        print '\t' * indent + str(key)
        if isinstance(value, dict):
            pretty(value, indent+1)
        else:
            print c
            if(c == steps):
                return
            c += 1
            print '\t' * (indent+1) + str(value)

which dreams of printing until a certain number of values of the original key are printed. For example, without a limit:

1
5299
    1
1229
    1
2068
    1
7223
    1

but when steps = 2, then it would print:

1
5299
    1
1229
    1

The reason its dreams are not coming true is that c is not a static variable (like one would do in C, I tried static c = 0 and got a syntax error), thus at every call of the recursion, c is created again, it doesn't remember its former value.

How would one do this in Python?

Community
  • 1
  • 1
gsamaras
  • 71,951
  • 46
  • 188
  • 305
  • 1
    Couldn't you pass `c` to the function as well so it's "re-supplied" at every recursion and incremented? – jDo May 01 '16 at 21:37
  • Yeah @jDo, that did the trick, would you lay an answer or should I delete the question? It was marked as a duplicate! – gsamaras May 01 '16 at 21:39
  • 1
    Cool. I don't think I *can* answer when the question is marked as a duplicate; it's also discouraged to do so. Anyway, I don't see anything related to recursion in the duplicate... If you think the duplicate question would actually have solved your issue, delete your question; otherwise, don't. That's just my advice, not necessarily SO policy or anything. – jDo May 01 '16 at 21:57

0 Answers0