2

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).

1 Answer 1

5

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))
Sign up to request clarification or add additional context in comments.

5 Comments

Thank you, but what do you mean by 'pythonic'? Is that the way python is supposed to be written?
you could also use while True' and itertools.islice()
@J.F.Sebastian Yes that was suggested to me as an edit but would it not overcomplicate this or do you think it is a better approach and for what reasons?
it provides a better code separation e.g., you could use the same code to find all fibonacci numbers less than 1000.
@J.F.Sebastian Ok then that will be added in later.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.