Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemath
GitHub Repository: sagemath/sagelib
Path: blob/master/sage/combinat/generator.py
4045 views
1
"""
2
Generators
3
"""
4
#*****************************************************************************
5
# Copyright (C) 2007 Mike Hansen <[email protected]>,
6
#
7
# Distributed under the terms of the GNU General Public License (GPL)
8
#
9
# This code is distributed in the hope that it will be useful,
10
# but WITHOUT ANY WARRANTY; without even the implied warranty of
11
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12
# General Public License for more details.
13
#
14
# The full text of the GPL is available at:
15
#
16
# http://www.gnu.org/licenses/
17
#*****************************************************************************
18
19
def concat(gens):
20
r"""
21
Returns a generator that is the concatenation of the generators in
22
the list.
23
24
EXAMPLES::
25
26
sage: list(sage.combinat.generator.concat([[1,2,3],[4,5,6]]))
27
[1, 2, 3, 4, 5, 6]
28
"""
29
30
for gen in gens:
31
for element in gen:
32
yield element
33
34
35
def map(f, gen):
36
"""
37
Returns a generator that returns f(g) for g in gen.
38
39
EXAMPLES::
40
41
sage: f = lambda x: x*2
42
sage: list(sage.combinat.generator.map(f,[4,5,6]))
43
[8, 10, 12]
44
"""
45
for element in gen:
46
yield f(element)
47
48
def element(element, n = 1):
49
"""
50
Returns a generator that yield a single element n times.
51
52
EXAMPLES::
53
54
sage: list(sage.combinat.generator.element(1))
55
[1]
56
sage: list(sage.combinat.generator.element(1, n=3))
57
[1, 1, 1]
58
"""
59
for i in range(n):
60
yield element
61
62
def select(f, gen):
63
"""
64
Returns a generator for all the elements g of gen such that f(g) is
65
True.
66
67
EXAMPLES::
68
69
sage: f = lambda x: x % 2 == 0
70
sage: list(sage.combinat.generator.select(f,range(7)))
71
[0, 2, 4, 6]
72
"""
73
for element in gen:
74
if f(element):
75
yield element
76
77
78
def successor(initial, succ):
79
"""
80
Given an initial value and a successor function, yield the initial
81
value and each following successor. The generator will continue to
82
generate values until the successor function yields None.
83
84
EXAMPLES::
85
86
sage: f = lambda x: x+1 if x < 10 else None
87
sage: list(sage.combinat.generator.successor(0,f))
88
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
89
"""
90
yield initial
91
92
s = succ(initial)
93
while s:
94
yield s
95
s = succ(s)
96
97
98
99