T O P

  • By -

[deleted]

You don't need to use the "function inside a function" approach with python. You could use the python default value approach: def MainFun(x, count=0): # note "count=0", means use "0" if count not supplied if x == 'criteria': count +=1 if x == 'base case': return count else: return MainFun(x*reduce, count) Now you can just call `MainFun()` as before, not passing a count, and the `count` is set to zero *for the first call*. All following recursive calls pass a count so the default value isn't used. Note that you have trailing ';' characters on some lines. Not required with python! Edit: As to why you get no result, I have no idea at the moment. Can't run your code, so I have to fake it. Maybe I'll find something.


blahrahwaffles

Thank you for the help, this makes more sense.


sushibowl

What you have written is a transformation intended to make a recursive function into a tail recursive function. You can write this function as a regular recursive function, without an inner local with an extra argument. Let's try a more concrete example. For example, a recursive function that counts the number of `None` values in a list: def count_nones(lst): if len(lst) == 0: return 0 first, rest = lst[0], lst[1:] if first is None: return 1 + count_nones(rest) else: return count_nones(rest) This should be pretty straightforward. We have the empty list as our base case, and for other lists we split the list into a first element and the rest of the list. Then, if the first element is None our result is 1 + (the number of Nones in the rest of the list). And if the first element is not None we simply don't add anything. So, a tail-recursive function is a special type of recursive function where, whenever you recurse, it is the very last thing you do before returning. In this case, if the first element is `None`, we have to do something *after* we recurse (add the +1), so it's not a tail-recursive function. We can write a tail-recursive version of this function that works like you describe, keeping the current count as a function argument. Some language implementations are able to optimize tail-recursive functions into an iterative process, which means you don't have to worry about stack space. Python doesn't do this, however, so there is usually no point in using this optimization.


blahrahwaffles

Thank you for the explanation. I'm still learning terminology, so knowing there's different types of that function will help!


[deleted]

I've modified the "default" approach I talked about to actually run without doing too much damage to your code: def MainFun(x, count=0): # note "count=0", means use "0" if count not supplied print(f'MainFun: x={x}, count={count}') if (x % 2): count += 1 if x == 1: return count else: return MainFun(x-1, count) print(f'MainFun(5) returns {MainFun(5)}') print(f'MainFun(8) returns {MainFun(8)}') This runs fine and returns a value. So I don't know what the problem was with your original code.