Skip to content

Instantly share code, notes, and snippets.

@vilcans
Created May 25, 2011 19:53
Show Gist options
  • Save vilcans/991768 to your computer and use it in GitHub Desktop.
Save vilcans/991768 to your computer and use it in GitHub Desktop.
Comparing recursive and iterative fibonacci functions
# Calculate a number in a Fibonacci series,
# starting at fib(0) == 0 and fib(1) == 1.
# An iterative and a recursive implementation.
# Which one most clearly shows what the code does?
def iterative_fibonacci(x):
a, b = 0, 1
for n in range(x):
a, b = b, a + b
return a
def recursive_fibonacci(x):
if x == 0:
return 0
elif x == 1:
return 1
else:
return recursive_fibonacci(x - 1) + recursive_fibonacci(x - 2)
# The first lines of recursive_fibonacci could be replaced by
#
# if x in (0, 1):
# return x
#
# but IMO it makes the code less clear.
# fib(x)==x happens to be true for x in (0, 1) but it's normally not written
# like that when you define the Fibonacci series.
# Tests
for fib in (iterative_fibonacci, recursive_fibonacci):
result = [fib(x) for x in range(8)]
assert [0, 1, 1, 2, 3, 5, 8, 13] == result, 'result for ' + str(fib) + ': ' + str(result)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment