简体   繁体   中英

Writing Fibonacci Sequence to a file Python?

I've been having some struggle getting each number in the Fibonacci sequence to write to a file, I know there is something I'm doing wrong, but I can't pinpoint it. Is there a more efficient approach? Any help is appreciated.

import sys
import os
import time

known = {0:0, 1:1}

def fibonacci_slow(n):
    if n == 0:
        return 0
    elif n == 1:
        return 1
    else:
        return fibonacci_slow(n-1) + fibonacci_slow(n-2)

def fibonacci_fast(n):
    f = open('fib500.txt', 'w')
    if n in known:
        return known[n]
    res = fibonacci_fast(n-1) + fibonacci_fast(n-2)
    print res
    if fibonacci_fast:
        f.write(res)
    known[n] = res
    return res

def main():
    time_start = time.time()
    print fibonacci_slow(10)
    time_end = time.time()
    print "Time for slow fibonacci to complete ", time_end - time_start

    time_start = time.time()
    print fibonacci_fast(500)

    time_end = time.time()
    print "Time for fast fibonacci to complete ", time_end - time_start


if __name__ == '__main__':
    main()

You need to take the writing into the file out of the fibonacci_fast method. Each time you call it, it re-opens the file and, since you didn't close it, there is no guarantee that it will be written into the file.

As for speed, recursion is not a good fit for your calculations. You don't need the recursive call:

res = fibonacci_fast(n-1) + fibonacci_fast(n-2)

because you could have already come up with the return value of those calls. It would be better to start from the beginning and working until you get to the value that you want, without suffering the overhead caused by this kind of recursion. In other words, it would be faster to take an iterative approach.

As you are probably trying to show, generating the n-th number in the Fibonacci sequence is not a good candidate for recursion, in the sense of speed/optimization.

If you change your fibonacci_fast to something like:

def fibonacci_fast(n):
    known = [0, 1]
    count = 0
    for i in range(n):
        newNum = known[0] + known[1]
        known[0] = known[1]
        known[1] = newNum
    return known[0]

and running your test script:

def main():
    time_start = time.time()
    print fibonacci_slow(20)
    time_end = time.time()
    print "Time for slow fibonacci to complete ", time_end - time_start

    time_start = time.time()
    print fibonacci_fast(20)
    time_end = time.time()
    print "Time for fast fibonacci to complete ", time_end - time_start

you get:

6765
Time for slow fibonacci to complete  0.0043318271637
6765
Time for fast fibonacci to complete  0.00010085105896

and to write it to a file you can add a file argument which you can write to:

def fibonacci_fast(n, f):
    known = [0, 1]
    for i in range(n):
        newNum = known[0] + known[1]
        known[0] = known[1]
        known[1] = newNum
        f.write(str(known[0]) + " ")
    return known[0]

and call it like so:

f = open("fib.txt", "w")
fibonacci_fast(20, f)
f.close()

or the more 'pythonic' way (which is a little bit faster):

with open("fib.txt", "w") as f:
    fibonacci_fast(20, f)

You can see the big difference between the recursive and iterative approach if you try to generate the 500th number in the sequence. It takes minutes (if not hours, I haven't waited it out) to finish the recursive function but only a fraction of a fraction of a second to do the iterative method, even with writing it to a file.

More information on the fibonacci sequence can be found here.

Your recursion is a bit clumsy, recalculates every number a lot of times. It's a classical problem, this iterative algorithm would work:

def fib2file(n, fname):
    with open(fname, 'w') as of:
        f1, f2, f3 = 0, 1, 0
        for _ in range(n):
            f1 = f2
            f2 = f3
            f3 = f1 + f2
            of.write('%d\n' % f3)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM