JessLovely
JessLovely

Reputation: 142

How to count repetitions of a recursive function?

So I have this function (example):

def monty(x):
  if abs(int(x)) == 1:
    print("Cool!")
    print("Took %s attempts.") % (z)
  elif abs(int(x)) == 0:
    print("Nope.")
  else:
    z = z + 1
    y = x - 1
    monty(y)

Now, of course, 'z' has not yet been defined, so when this function is run so that the 'else' statement is called, the program returns a NameError exception.

Well, ok. Let's try making the statement this:

else:
  try: z
  except NameError: z = 0
  else: z = z + 1
  y = x - 1
  monty(y)

Also assume we added the same NameError catch to the 'if' statement.

The statement always returns 'z' as 0, as the variable is utterly forgotten when 'monty' is ran again. Ok, what if we try defining z outside of 'monty' first, and drop the NameError catch?

Well, it returns a NameError again, and if we instead keep the NameError catch, it still only ever outputs 0.

So, how do I make the function increase z every time it's called validly? In other words, how can I have the program silently count how many times a function was run, to be recalled later? Let's try to avoid adding another argument to the function, for the sake of user-friendliness.

Upvotes: 0

Views: 298

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121524

Just add z as a keyword argument:

def monty(x, _z=0):
    # ...
    else:
        _z = _z + 1
        y = x - 1
        monty(y, _z)

I renamed z to _z to indicate that it is an implementation detail the end-user doesn't need to worry about. Because keyword arguments have a default, the caller of monty() doesn't have to worry about it.

Upvotes: 3

Related Questions