Created
July 10, 2012 10:27
-
-
Save tucano/3082523 to your computer and use it in GitHub Desktop.
fibonacci test for generators in python
This file contains 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
#!/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