简体   繁体   中英

Checking efficiency of a Python Fibonacci Sequence Generator?

I am new to python and to programming all together. I am wondering if this is a terribly inefficient way of generating Fibonacci numbers for a beginner?

a = 1
b = 1
total = 0
counter = input("Please enter the term you wish to end at: ")
print "1"
print""
print "1"
number = 2

while counter > number:
    total = a+b
    print ""
    print total
    a = b
    b = total
    number = number + 1

If so, can someone point out a few things such as:

What to research/Google to make my code more efficient.

Suggest programming practices that I need to work on (I know this isn't a huge sample of my work).

With python you do not want to worry about efficiency as much as you would in C for example, although you still want to achieve the shortest Big Oh running time. The way you have written this is around as efficient as you can get so you don't need to worry about that too much. However, it is not very pythonic with the use of while to add to a counter.

This can be written more simply as:

a, b = 0, 1
counter = input("Please enter the term you wish to end at: ")
for _ in xrange(counter): #xrange is more efficient than range, the number is not used so _ is used to show that
    a, b = b, a+b
    print a
    print

You could also use a generator for this, which might be a programming practice you could work on...

def fib(end):
    a, b = 0, 1
    for _ in xrange(end):
        a, b = b, a+b
        yield str(a)

counter = input("Please enter the term you wish to end at: ")    
print '\n\n'.join(fib(counter))

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