Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit ee30927

Browse files
committed
Another variant of the 2-3-5 test, mixing generators with a LazyList class.
Good news: Some of this stuff is pretty sophisticated (read nuts), and I haven't bumped into a bug yet. Bad news: If I run the doctest in an infinite loop, memory is clearly leaking.
1 parent 7e82b9c commit ee30927

1 file changed

Lines changed: 37 additions & 0 deletions

File tree

Lib/test/test_generators.py

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -405,8 +405,45 @@
405405
[81, 90, 96, 100, 108, 120, 125, 128, 135, 144, 150, 160, 162, 180, 192]
406406
[200, 216, 225, 240, 243, 250, 256, 270, 288, 300, 320, 324, 360, 375, 384]
407407
[400, 405, 432, 450, 480, 486, 500, 512, 540, 576, 600, 625, 640, 648, 675]
408+
409+
Heh. Here's one way to get a shared list, complete with an excruciating
410+
namespace renaming trick. The *pretty* part is that the times() and merge()
411+
functions can be reused as-is, because they only assume their stream
412+
arguments are iterable -- a LazyList is the same as a generator to times().
413+
414+
>>> class LazyList:
415+
... def __init__(self, g):
416+
... self.sofar = []
417+
... self.fetch = g.next
418+
...
419+
... def __getitem__(self, i):
420+
... sofar, fetch = self.sofar, self.fetch
421+
... while i >= len(sofar):
422+
... sofar.append(fetch())
423+
... return sofar[i]
424+
425+
>>> def m235():
426+
... yield 1
427+
... # Gack: m235 below actually refers to a LazyList.
428+
... me_times2 = times(2, m235)
429+
... me_times3 = times(3, m235)
430+
... me_times5 = times(5, m235)
431+
... for i in merge(merge(me_times2,
432+
... me_times3),
433+
... me_times5):
434+
... yield i
435+
436+
>>> m235 = LazyList(m235())
437+
>>> for i in range(5):
438+
... print [m235[j] for j in range(15*i, 15*(i+1))]
439+
[1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20, 24]
440+
[25, 27, 30, 32, 36, 40, 45, 48, 50, 54, 60, 64, 72, 75, 80]
441+
[81, 90, 96, 100, 108, 120, 125, 128, 135, 144, 150, 160, 162, 180, 192]
442+
[200, 216, 225, 240, 243, 250, 256, 270, 288, 300, 320, 324, 360, 375, 384]
443+
[400, 405, 432, 450, 480, 486, 500, 512, 540, 576, 600, 625, 640, 648, 675]
408444
"""
409445

446+
410447
__test__ = {"tut": tutorial_tests,
411448
"pep": pep_tests,
412449
"email": email_tests,

0 commit comments

Comments
 (0)