banner
NEWS LETTER

Python防爆栈模板

Scroll down

简介

类似协程, 可以yield结果, 记得return.

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
from typing import Generator, Any



def calc(n):
if n <= 1:
return n
else:
a = yield calc(n - 1)
return a + 1


def event_loop(start_gen: Generator):
stack: list[Generator] = [start_gen]

last_result: Any = None

while stack:
now_task = stack[-1]
try:
next_val = now_task.send(last_result)
last_result = None
if isinstance(next_val, Generator):
stack.append(next_val)
else:
last_result = next_val
stack.pop()

except StopIteration as e:
stack.pop()

last_result = e.value

except TypeError as e:
if (
last_result is None
and "can't send non-None value to a just-started generator"
not in str(e)
):
last_result = None
continue
else:
raise e

return last_result


print(f"Final result: {event_loop(calc(1000000))}")

我很可爱,请给我钱

其他文章
目录导航 置顶
  1. 1. 简介
  2. 2. 代码