Найти в Дзене
10 подписчиков

📑 Recursive Infinite Generators

📑 Task
1) What is the last number the program will print?
2) What object appears when this function is applied
3) Can you write a program for an infinite generator of fibonacci numbers
without recursion but limit the number of iterations?

def fibonacci_gen(x=0, y=1):
yield x
yield from fibonacci_gen(y, x + y)
fg = fibonacci_gen()
for _ in range(10):
print(next(fg), end=' ')

📑 Answer
1) 34
2) It is a recursive infinite generator
3)

def fibonacci_gen_step(x=0, y=1, steps=7):
step = 1; yield x
while True:
if step == steps:
return
else:
step += 1
x, y = y, x + y
yield x
fgs1 = fibonacci_gen_step()
for _ in range(7):
print(next(fgs1), end=' ')
print()
fgs2 = fibonacci_gen_step()
for _ in range(10):
try:
print(next(fgs2), end=' ')
except StopIteration:
print(f"\nmaximum number of generator iterations = {_}")
break
📑 Recursive Infinite Generators python-puzzles.blogspot.com/...tml 📑 Task 1) What is the last number the program will print?
Около минуты