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

Sam
  • 7,252
  • 16
  • 46
  • 65

1 Answers1

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))
jamylak
  • 128,818
  • 30
  • 231
  • 230
  • Thank you, but what do you mean by 'pythonic'? Is that the way python is supposed to be written? – Pedopenguin Jun 02 '12 at 11:06
  • you could also use [`while True'`](http://stackoverflow.com/a/250041/4279) and itertools.islice() – jfs Jun 03 '12 at 12:58
  • @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? – jamylak Jun 03 '12 at 13:02
  • it provides a better code separation e.g., you could use the same code to find all fibonacci numbers less than 1000. – jfs Jun 03 '12 at 13:04
  • @J.F.Sebastian Ok then that will be added in later. – jamylak Jun 03 '12 at 13:08