Last active
December 26, 2018 07:40
-
-
Save o3o3o/4a0ccff1e4f2dbfab6e125bf9de07d4c to your computer and use it in GitHub Desktop.
tail recurse exercise
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| """ | |
| fun fib(n) = | |
| if n=1 then 1 | |
| else if n=2 then 1 | |
| else fib(n-1) + fib(n-2) | |
| """ | |
| def fib_loop(n): | |
| a = 1 | |
| b = 2 | |
| for i in xrange(1, n): | |
| a, b = a+b, a | |
| return a | |
| def fib2(n): | |
| if n in [1,2]: | |
| return 1 | |
| return fib2(n-1) + fib2(n-2) | |
| def fib2_tail_recurse(n, res=1, t=1): | |
| if n==1: | |
| return res | |
| elif n==2: | |
| return res | |
| else: | |
| return fib2_tail_recurse(n-1, res+t, res) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment