Add examples of deeply nested generators. #453
Closed
+297
−1
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Background: According to this post, it seems that PEP 380 Optimizations have not been implemented in CPython yet. I tested the following code in Python 3.12, proving that its time complexity should be$O(n^2)$ , and it requires calling $n$ is big enough.
sys.setrecursionlimitto increase the recursion depth limit whenAs is shown in$O(n)$ time and does not require increasing the recursion depth limit (it still needs $O(n)$ extra space but it's on the heap).
test_generator_deeply_nested.py,make_integer_sequencedoes the same as the code above, but it only costsAs to
test_generator_deeply_nested2.py, it uses the built-inyield, only convertingyield from. Its time and space cost is similar to the previous one, and the difference is that its constant factor seems smaller than the previous one, running much faster for large input. On my personal device, forn = 1_000_000,make_integer_sequenceintest_generator_deeply_nested.pytakes ~5x time compared with that intest_generator_deeply_nested2.py.