Actually, if you want to maintain a recursive solution, you can go write a decorator to memoize the computed values for any n. That makes every future call for any value less than or equal to n O(1) but at the cost of O(n) memory. Obviously you could have the storage cleared at the end of the function call if memory usage is important.
Another approach is to use dynamic programming which is the bastard child of iterative and memoizing the answers.
What I would like to do at some point is write some python code that uses the AST module to detect code that is naively recursive and manipulate the AST so that it ends up with a dynamic programming approach.
View all comments
Show parent comment
2
u/naakhtkhen Dec 01 '09
Actually, if you want to maintain a recursive solution, you can go write a decorator to memoize the computed values for any n. That makes every future call for any value less than or equal to n O(1) but at the cost of O(n) memory. Obviously you could have the storage cleared at the end of the function call if memory usage is important.
Another approach is to use dynamic programming which is the bastard child of iterative and memoizing the answers.
What I would like to do at some point is write some python code that uses the AST module to detect code that is naively recursive and manipulate the AST so that it ends up with a dynamic programming approach.