As I told - one way is to use memoization. It seems to me that if you are 'told' then it's homework therefore I provide a solution which has caveats and may not pass automated test system:
def factorial(n, d={0:1, 1:1}): if n < 0: raise ValueError('No factorials for negative numbers!') if n in d: print(f'n is {n}, carry over {d[n]}, this is base case') return d[n] else: value = factorial(n-1, d) * n d[n] = value print(f'n is {n}, carry over {n} * {d[n-1]} = {d[n]}') return valueThis gives:
>>> factorial(5) n is 1, carry over 1, this is base case n is 2, carry over 2 * 1 = 2 n is 3, carry over 3 * 2 = 6 n is 4, carry over 4 * 6 = 24 n is 5, carry over 5 * 24 = 120 120 >>> factorial(0) n is 0, carry over 1, this is base case 1 >>> factorial(-5) /.../ ValueError: No factorials for negative numbers! # But! Second time in same session: >>> factorial(5) n is 5, carry over 120, this is base case 120 >>> factorial(6) n is 5, carry over 120, this is base case n is 6, carry over 6 * 120 = 720 720
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy
Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.