Python Use a Generator to Implement an Infinite Sequence
In Python, a generator is a special kind of iterator that allows you to generate values on demand rather than generating all of them at once. Generators are well suited for handling infinite sequences because they only generate values when needed, saving memory.
The following is an example of using a generator to implement an infinite sequence that starts from 0 and increments by 1 each time.
Example
def
infinite_sequence
(
)
:
num
=
0
while
True
:
yield
num
num +
=
1
Code analysis:
def infinite_sequence():defines a class namedinfinite_sequencegenerator function.num = 0Initialize a variablenum, 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 returns the currentnumvalue and pauses the function's execution until the next call tonext()。num += 1Each time a value is generated,numincrements by 1 so that the next value is generated next time.
Output result: Since this is an infinite sequence, the generator will keep generating values. You can use the next() function to get the next value in the sequence.
gen = infinite_sequence()
print(next(gen)) # 输出: 0
print(next(gen)) # 输出: 1
print(next(gen)) # 输出: 2
# For example...
Each time you call next(gen) , the generator resumes execution from where it last paused and returns the next value.
Python3 Examples