0

I apologize for the simplicity of this question, I have searched multiple times but it may be so simple it hasn't been asked before.

I wrote a Fibonacci function that prints every Fibonacci number under 3000.

def fibonacci():
    a, b = 0, 1
    while b < 3000:
        a, b = b, a + b
        print a
    return a

How can I make it so it returns the first n Fibonacci numbers?

Also, how can I make it just print the nth value? For example print [6], which would return 8. I tried to make it a string:

a = str(fibonacci())
print a[6]

but that didn't work, and I'm not sure why. Thanks for helping.

  • Print prints the intermediate results to standard output, but otherwise they are lost. You'll have to store them somewhere. – flup Jul 21 '13 at 23:52
  • 1
    possible duplicate of [Python Fibonacci Generator](http://stackoverflow.com/questions/3953749/python-fibonacci-generator) – flup Jul 21 '13 at 23:54
  • You can use `yield` in a method to turn the results into a iterable generator – cdbitesky Jul 21 '13 at 23:55
  • That makes sense, but I am such a novice I'm not sure how I'd go about doing that. How do you store all the intermediate results? – ChillerObscuro Jul 21 '13 at 23:55

4 Answers4

0

First, your function needs to know what n to use. That's simple enough - just tell it n as an argument:

def fibonacci(n):

If you want to return the first n fibonacci numbers, you'll need to keep a list of them:

    numbers = [0, 1] # Start off with the first 2 numbers

Then, compute the fibonacci numbers pretty much the way you did before, except stopping at the nth one, and adding together the last two list elements instead of a and b:

    # xrange(2, n) is a sequence going from 2 to n-1
    for i in xrange(2, n):
        # Add together the last two fibonacci numbers and append the result
        # to the list
        numbers.append(numbers[-2] + numbers[-1])

Finally, return the list:

    return numbers

The end result:

def fibonacci(n):
    numbers = [0, 1]
    for i in xrange(2, n):
        numbers.append(numbers[-2] + numbers[-1])
    return numbers

This will return a list of the first n fibonnaci numbers (for n >= 2). You'll need to special-case n == 0 or n == 1 if you want to handle those values.

user2357112
  • 260,549
  • 28
  • 431
  • 505
0

You could turn your function into a generator and use it in a list comprehension. The last number in the list created is the value of nth fibonacci number (fibonacci(n)):

def fibonacci(n):
    a, b = 0, 1
    count = 0
    while count < n:
        a, b = b, a + b
        count += 1
        yield a

fibs = [fib for fib in fibonacci(6)]
print fibs
print 'fibonacci(6):', fibs[-1]

Output:

[1, 1, 2, 3, 5, 8]
fibonacci(6): 8
martineau
  • 119,623
  • 25
  • 170
  • 301
0

Create a generator:

def fibonacci():
    a, b = 0, 1
    while True:
        a, b = b, a + b
        yield a

Create a wrapper to call it n times

def fibn(n):
    g= fibonacci()
    return [next(g) for _ in xrange(n)][-1]

>>> fibn(5)
5
>>> fibn(15)
610
dansalmo
  • 11,506
  • 5
  • 58
  • 53
0

There are several ways to do this; here's a semi-clever one:

First, change print to yield, so the function returns the numbers instead of printing them:

def ifibonacci():
    a, b = 0, 1
    while b < 3000:
        a, b = b, a + b
        yield a

Then use itertools.islice to slice out the numbers you want:

import itertools

print list(itertools.islice(ifibonacci(), 10))
# prints [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]

print list(itertools.islice(ifibonacci(), 6, 6+1))
# prints [13] which isn't quite right; see below

Note that your function doesn't output the initial 0, so the indexes are off by one. To fix that, move the yield up one line:

def ifibonacci():
    a, b = 0, 1
    while b < 3000:
        yield a
        a, b = b, a + b

print list(itertools.islice(ifibonacci(), 6, 6+1))
# prints [8]

(also, this still won't print numbers larger than 3000. fixing that is left as an exercise)

Fredrik
  • 940
  • 4
  • 10