We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Same solution with cached memmory so the function doesn't have to repeat itself every time:
factorial_cache={}deffactorial(n):# Memoization: Return the value we have cachedifninfactorial_cache:returnfactorial_cache[n]# Factorial Partifn<=1:value=1else:value=n*factorial(n-1)# Cache the valuefactorial_cache[n]=valuereturnvalue
In my original code I wrote print('1') instead of return 1 and the compiler showed error. Can somebody tell me why this happened. It showed * can't be done in between an int and a nontype
Well then I think the condition should be n == 1 or n == 0. As n <= 1 will also take negative numbers into consideration whose factorials cannot be calculated.
Day 9: Recursion 3
You are viewing a single comment's thread. Return to all comments →
In Python 3.
We know that factorial of 1 and 0 is 1, after that we have what we have
this is awesome <3
Nice job. However, you can skip the result variable and just return the arithmetic.
return n * factorial(n - 1)
This code won't stop until it exceeded the recursion depth as you didn't give it a stop point.
Can you explain how the
factorial
inresult = n * factorial(n - 1)
works?By the time the computer traverses to
factorial
, the function hasn't been finished defining.Thanks!
use memoization or lru_cache to reduce the usage of processing power
Same solution with cached memmory so the function doesn't have to repeat itself every time:
In my original code I wrote print('1') instead of return 1 and the compiler showed error. Can somebody tell me why this happened. It showed * can't be done in between an int and a nontype
showing error no response on stdoutput
def factorial(n): fact = 1 if n < 0: return "Not Exist" elif n == 0: return 1 else: for i in range(1, n + 1): fact *= i return fact
Non recursive
presized
Well then I think the condition should be n == 1 or n == 0. As n <= 1 will also take negative numbers into consideration whose factorials cannot be calculated.
i started from factorial 1. here is my code:
Javascript with memoization (Dynamic Programming) for better performance: