from types import GeneratorType
def iterative(f, stack=[]):
def wrapped_func(*args, **kwargs):
if stack: return f(*args, **kwargs)
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
continue
stack.pop()
if not stack: break
to = stack[-1].send(to)
return to
return wrapped_func
Selle kasutamiseks tuleb oma rekursiivne funktsioon kirjutada nii nagu ikka, aga funktsiooni algusesse annotatsioon @iterative, ning rekursiivsete kutsete jaoks tuleb kasutada yield. Näiteks
@iterative
def dfs (u):
if visited[u]:
yield
for nxt in graph[u]:
yield dfs(u)
# teen ehk veel mingeid asju jne
yield
Lehekülg viimati muudetud July 06, 2024, at 02:33 PM