Skip to content

Instantly share code, notes, and snippets.

@tucano
Created July 10, 2012 10:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tucano/3082523 to your computer and use it in GitHub Desktop.
Save tucano/3082523 to your computer and use it in GitHub Desktop.
fibonacci test for generators in python
#!/usr/bin/env python
# encoding: utf-8
"""
fibonacci.py
RECURSIVE or GENERATOR?
Created by drambald on 2012-07-10.
Copyright (c) 2012 tucanosoftware.com. All rights reserved.
"""
import sys
import os
import time
def main_recursive():
for x in range(30):
print "fibonacci(%d) = %d" % (x, fibonacci(x))
# RECURSIVE
def fibonacci(n):
if n < 2:
return n
else:
return fibonacci(n - 1) + fibonacci(n - 2)
def main_generator():
f = fiboyield()
for x in range(30):
print "fibonacci: %d" % f.next()
# GENERATOR
def fiboyield():
x,y = 0,1
while True:
yield x
x, y = y, x + y
# RUN RUN RUN
start_time = time.time()
main_recursive()
print time.time() - start_time, "seconds"
new_time = time.time()
main_generator()
print time.time() - new_time, "seconds"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment