I observe following problematic areas:
- base case is not printed out (one can't understand if whole 'process' is not printed out)
- this function is not defensive against negative values (RecursionError)
For better understanding one can write (requires 3.6 <= Python due to f-strings):
- base case is not printed out (one can't understand if whole 'process' is not printed out)
- this function is not defensive against negative values (RecursionError)
For better understanding one can write (requires 3.6 <= Python due to f-strings):
def _factorial_sample_(n): if n < 0: raise ValueError('No factorials for negative numbers') if n == 0 or n == 1: print(f'n is {n}, carrying over {1}, this is base case') return 1 else: result = n * _factorial_sample_(n-1) print(f'n is {n}, carrying over {result}') return resultWith different arguments one will get:
>>> _factorial_sample_(5) n is 1, carrying over 1, this is base case n is 2, carrying over 2 n is 3, carrying over 6 n is 4, carrying over 24 n is 5, carrying over 120 120 >>> _factorial_sample_(0) n is 0, carrying over 1, this is base case 1 >>> _factorial_sample_(1) n is 1, carrying over 1, this is base case 1 >>> _factorial_sample_(-5) /.../ ValueError: No factorials for negative numbersTo your original problem: you probably should use memoization
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.