Implementing A Fibonacci Number Generator

Fibonacci Numbers: Naive List

#!/usr/bin/python

def fibonacci():
    fibo_numbers = []

    previous = 1
    current = 1
    while True:
        next = previous + current
        fibo_numbers.append(next)
        previous, current = current, next
        
    return fibo_numbers

if __name__ == '__main__':
    for num in fibonacci():
        print(num)
  • watch OS become overly jerky, until process is OOM-killed

  • well, there’s need for a limit

Fibonacci Numbers: Naive List, Limited

#!/usr/bin/python

def fibonacci(max_numbers=100):
    fibo_numbers = []

    previous = 1
    current = 1
    while len(fibo_numbers) < max_numbers:
        next = previous + current
        fibo_numbers.append(next)
        previous, current = current, next
        
    return fibo_numbers

if __name__ == '__main__':
    for num in fibonacci():
        print(num)

Sideway: Infinity by Not Using Functions

  • Still not satisfactory

  • Want infinity

  • Can be done, by embedding the using code (print()) into the Fibonacci generation.

  • not so modular though

#!/usr/bin/python

previous = 1
current = 1

while True:
    next = previous + current
    print(next)
    previous, current = current, next

Fibonacci Numbers: Function Producing Infinite Sequence

#!/usr/bin/python

def fibonacci():
    previous = 1
    current = 1
    while True:
        next = previous + current
        yield next
        previous, current = current, next

if __name__ == '__main__':
    for num in fibonacci():
        print(num)

Common Pattern: Turn List into Generated Items

  • correct infinity can save a few lines

--- /home/jfasch/My-Projects/jfasch-home/trainings/material/soup/python/advanced/iteration-generation/python_1010_generators_yield/code/10-fibo-list-nolimit.py
+++ /home/jfasch/My-Projects/jfasch-home/trainings/material/soup/python/advanced/iteration-generation/python_1010_generators_yield/code/40-fibo-generator.py
@@ -1,16 +1,12 @@
 #!/usr/bin/python
 
 def fibonacci():
-    fibo_numbers = []
-
     previous = 1
     current = 1
     while True:
         next = previous + current
-        fibo_numbers.append(next)
+        yield next
         previous, current = current, next
-        
-    return fibo_numbers
 
 if __name__ == '__main__':
     for num in fibonacci():