Code Explanation:
1. Import from itertools
from itertools import takewhile
This imports the takewhile() function from Python’s itertools module.
takewhile(predicate, iterable) returns items from an iterable as long as the predicate is true.
The moment the condition fails, it stops.
2. Define Generator Function
def infinite():
This line defines a generator function named infinite.
Generator functions yield values one at a time and pause after each yield.
3. Initialize and Yield Values
i = 1
while True:
yield i
i *= 2
i = 1: Start with the number 1.
while True: This loop runs forever (until manually stopped).
yield i: Produces the current value of i, then pauses.
i *= 2: Doubles i for the next round (e.g., 1 → 2 → 4 → 8 → 16 → ...).
The generator will yield an infinite series of powers of 2:
1, 2, 4, 8, 16, 32, ...
4. Use takewhile() to Limit Output
print(list(takewhile(lambda x: x <= 10, infinite())))
takewhile(lambda x: x <= 10, infinite()):
Starts pulling values from infinite() one at a time.
Keeps collecting values while x <= 10.
Stops immediately when the first value exceeds 10 (which will be 16).
list(...): Converts the filtered generator output into a list.
print(...): Displays the result.
Final Output
[1, 2, 4, 8]
.png)

0 Comments:
Post a Comment