Python Using Generators to Implement an Infinite Sequence
In Python, a generator is a special type of iterator that allows you to generate values on demand rather than generating all values at once. Generators are very suitable for handling infinite sequences because they only generate values when needed, thus saving memory.
The following is an example of using a generator to implement an infinite sequence. The sequence starts at 0 and increments by 1 each time.
Example
def infinite_sequence():
num = 0
while True:
yield num
num += 1
num = 0
while True:
yield num
num += 1
Code analysis:
def infinite_sequence():Defines a function namedinfinite_sequencethat is a generator function.num = 0Initialize a variablenumthat is used to store the current value of the sequence.while True:Create an infinite loop to ensure the generator can keep generating values.yield numUseyieldkeyword to return the currentnumvalue, and pause the execution of the function until the next callnext()。num += 1After each value is generated,numincrement by 1 so that the next value can be generated next time.
Output result: Since this is an infinite sequence, the generator will keep generating values. You can use thenext()function to get the next value in the sequence.
gen = infinite_sequence() print(next(gen)) # 输出: 0 print(next(gen)) # 输出: 1 print(next(gen)) # 输出: 2 # 以此类推...
Every time you callnext(gen)the generator resumes execution from where it last paused and returns the next value.
Python3 Examples