fibonacci - How to get nth result from simple function in python? -


i apologize simplicity of question, have searched multiple times may simple hasn't been asked before.

i wrote fibonacci function prints every fibonacci number under 3000.

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

how can make returns first n fibonacci numbers?

also, how can make print nth value? example print [6], return 8. tried make string:

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

but didn't work, , i'm not sure why. helping.

there several ways this; here's semi-clever one:

first, change print yield, function returns numbers instead of printing them:

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

then use itertools.islice slice out numbers 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] isn't quite right; see below 

note function doesn't output the initial 0, indexes off one. fix that, move yield 1 line:

def ifibonacci():     a, b = 0, 1     while b < 3000:         yield         a, b = b, + b  print list(itertools.islice(ifibonacci(), 6, 6+1)) # prints [8] 

(also, still won't print numbers larger 3000. fixing left exercise)


Comments

Popular posts from this blog

html5 - What is breaking my page when printing? -

html - Unable to style the color of bullets in a list -

c# - must be a non-abstract type with a public parameterless constructor in redis -