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 50 51 52
| >>> def a_then_b(a,b): ... for x in a: ... yield x ... for x in b: ... yield x ... >>> list(a_then_b([1,2],[3,4])) [1, 2, 3, 4]
>>> def a_then_b(a,b): ... yield from a ... yield from b ... >>> list(a_then_b([1,2],[3,4])) [1, 2, 3, 4]
>>> def countdown(k): ... if k > 0: ... yield k ... for x in countdown(k-1): ... yield x ... >>> list(countdown(5)) [5, 4, 3, 2, 1]
>>> def countdown(k): ... if k > 0: ... yield k ... yield from countdown(k-1) ... >>> list(countdown(5)) [5, 4, 3, 2, 1]
>>> def prefixes(s): ... if s: ... yield from prefixes(s[:-1]) ... yield s ... >>> list(prefixes("tops")) ['t', 'to', 'top', 'tops']
>>> def substrings(s): ... if s: ... yield from prefixes(s) ... yield from substrings(s[1:]) ... >>> list(substrings("tops")) ['t', 'to', 'top', 'tops', 'o', 'op', 'ops', 'p', 'ps', 's']
|