Allow us to present a generator function for the Lucas series:
def lucas():
yield 2
a = 2
b = 1
while True:
yield b
a, b = b, a + b
The Lucas series starts with 2, 1, and each value after that is the sum of the two preceding values. So the first few value of the sequence are:
2, 1, 3, 4, 7, 11
The first yield produces the value 2. The function then initializes a and b which hold the "previous two values" needed as the function proceeds. Then the function enters an infinite while-loop where:
- It yields the value of b
- a and b are updated to hold the new "previous two" values using a neat application of tuple unpacking
Now that we have a generator, it can be used like any other iterable object. For instance, to print the Lucas numbers you could use a loop like this:
>>> for x in lucas():
... print(x)
...
2
1
3
4
7
11
18
29
47
76
123
199
Of course, since the Lucas sequence is infinite this will run forever, printing out values until your computer runs out of memory. Use Ctrl+C to terminate the loop.