# Fibonacci Generator

Page 1 of 1

## 0 Replies - 2350 Views - Last Post: 09 May 2012 - 09:06 PM

### #1 atraub

• Pythoneer

Reputation: 835
• Posts: 2,267
• Joined: 23-December 08

# Fibonacci Generator

Posted 09 May 2012 - 09:06 PM

Description: To get the next value from a generator, use the next function. y = fibonacciGenerator() firstFib = next(y) secondFib = next(y) etc...This simple function creates a generator that will yield fibonacci values!
```def fibonacciGenerator():
"""Simple Fibonacci Generator"""
twoBack,previous = 0,1

while True:
fibNumber = twoBack + previous
yield fibNumber
twoBack,previous = previous,fibNumber

```

Is This A Good Question/Topic? 0

## Replies To: Fibonacci Generator

### #2 atraub

• Pythoneer

Reputation: 835
• Posts: 2,267
• Joined: 23-December 08

## Re: Fibonacci Generator

Posted 09 May 2012 - 09:06 PM

Description: To get the next value from a generator, use the next function. y = fibonacciGenerator() firstFib = next(y) secondFib = next(y) etc...This simple function creates a generator that will yield fibonacci values!
```__author__ = "atraub"
__date__= "5/9/2012"

#optionally supply the first two values of generator to seed it
def fibonacciGenerator(previous=0,current=1):
"""Creates a Fibonacci Generator"""

#handle the first two values
if previous > current:
previous,current = current, previous

yield previous
yield current
current,previous = previous+current,current

#handle all subsequent values
while True:
yield current
current,previous = previous+current,current

```

### #3 atraub

• Pythoneer

Reputation: 835
• Posts: 2,267
• Joined: 23-December 08

## Re: Fibonacci Generator

Posted 09 May 2012 - 09:06 PM

Description: To get the next value from a generator, use the next function. y = fibonacciGenerator() firstFib = next(y) secondFib = next(y) etc...This simple function creates a generator that will yield fibonacci values!
```__author__ = "atraub"
__date__= "6/13/2012"

#optionally supply the first two values of generator to seed it
def fibonacciGenerator(previous=0,current=1):
"""Creates a Fibonacci Generator"""

#handle the first two values
if previous > current:
previous,current = current, previous

yield previous
yield current

#handle all subsequent values
while True:
current,previous = previous+current,current
yield current

```