Skip to content

Instantly share code, notes, and snippets.

@o3o3o
Last active December 26, 2018 07:40
Show Gist options
  • Select an option

  • Save o3o3o/4a0ccff1e4f2dbfab6e125bf9de07d4c to your computer and use it in GitHub Desktop.

Select an option

Save o3o3o/4a0ccff1e4f2dbfab6e125bf9de07d4c to your computer and use it in GitHub Desktop.
tail recurse exercise
"""
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