Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Fibonacci Generator

I need to make a program that asks for the amount of Fibonacci numbers printed and then prints them like 0, 1, 1, 2... but I can't get it to work. My code looks the following:

a = int(raw_input('Give amount: '))  def fib():     a, b = 0, 1     while 1:         yield a         a, b = b, a + b  a = fib() a.next() 0 for i in range(a):     print a.next(), 
like image 774
John Avatar asked Oct 17 '10 15:10

John


People also ask

How do you create a Fibonacci sequence in Python?

Here, we store the number of terms in nterms . We initialize the first term to 0 and the second term to 1. If the number of terms is more than 2, we use a while loop to find the next term in the sequence by adding the preceding two terms. We then interchange the variables (update it) and continue on with the process.

What is Fibonacci series in Python using function?

# Python program to display the Fibonacci sequence def recur_fibo(n): if n <= 1: return n else: return(recur_fibo(n-1) + recur_fibo(n-2)) nterms = 10 # check if the number of terms is valid if nterms <= 0: print("Plese enter a positive integer") else: print("Fibonacci sequence:") for i in range(nterms): print( ...

What is nth Fibonacci number in Python?

We have to find the nth Fibonacci term by defining a recursive function. So, if the input is like n = 8, then the output will be 13 as first few Fibonacci terms are 0, 1, 1, 2, 3, 5, 8, 13, 21, 34... otherwise, return solve(n - 1) + solve(n - 2)


2 Answers

I would use this method:

Python 2

a = int(raw_input('Give amount: '))  def fib(n):     a, b = 0, 1     for _ in xrange(n):         yield a         a, b = b, a + b  print list(fib(a)) 

Python 3

a = int(input('Give amount: '))  def fib(n):     a, b = 0, 1     for _ in range(n):         yield a         a, b = b, a + b  print(list(fib(a))) 
like image 59
rubik Avatar answered Sep 22 '22 12:09

rubik


You are giving a too many meanings:

a = int(raw_input('Give amount: ')) 

vs.

a = fib()        

You won't run into the problem (as often) if you give your variables more descriptive names (3 different uses of the name a in 10 lines of code!):

amount = int(raw_input('Give amount: ')) 

and change range(a) to range(amount).

like image 39
unutbu Avatar answered Sep 24 '22 12:09

unutbu