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

#1 atraub   User is offline

  • Pythoneer
  • member icon

Reputation: 833
  • View blog
  • Posts: 2,257
  • 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   User is offline

  • Pythoneer
  • member icon

Reputation: 833
  • View blog
  • Posts: 2,257
  • 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


Was This Post Helpful? 0
  • +
  • -

#3 atraub   User is offline

  • Pythoneer
  • member icon

Reputation: 833
  • View blog
  • Posts: 2,257
  • 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


Was This Post Helpful? 0
  • +
  • -

Page 1 of 1