Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemath
GitHub Repository: sagemath/sagesmc
Path: blob/master/src/sage/combinat/combinat.py
8817 views
1
r"""
2
Combinatorial Functions
3
4
This module implements some combinatorial functions, as listed
5
below. For a more detailed description, see the relevant
6
docstrings.
7
8
**Sequences:**
9
10
11
- Bell numbers, :func:`bell_number`
12
13
- Catalan numbers, :func:`catalan_number` (not to be
14
confused with the Catalan constant)
15
16
- Eulerian/Euler numbers, :func:`euler_number` (Maxima)
17
18
- Fibonacci numbers, :func:`fibonacci` (PARI) and
19
:func:`fibonacci_number` (GAP) The PARI version is
20
better.
21
22
- Lucas numbers, :func:`lucas_number1`,
23
:func:`lucas_number2`.
24
25
- Stirling numbers, :func:`stirling_number1`,
26
:func:`stirling_number2`.
27
28
**Set-theoretic constructions:**
29
30
- Derangements of a multiset, :func:`derangements` and
31
:func:`number_of_derangements`.
32
33
- Tuples of a multiset, :func:`tuples` and
34
:func:`number_of_tuples`. An ordered tuple of length k of
35
set S is a ordered selection with repetitions of S and is
36
represented by a sorted list of length k containing elements from
37
S.
38
39
- Unordered tuples of a set, :func:`unordered_tuples` and
40
:func:`number_of_unordered_tuples`. An unordered tuple
41
of length k of set S is an unordered selection with repetitions of S
42
and is represented by a sorted list of length k containing elements
43
from S.
44
45
.. WARNING::
46
47
The following functions are deprecated and will soon be removed.
48
49
- Combinations of a multiset, :func:`combinations`,
50
:func:`combinations_iterator`, and :func:`number_of_combinations`. These
51
are unordered selections without repetition of k objects from a multiset
52
S.
53
54
- Arrangements of a multiset, :func:`arrangements` and
55
:func:`number_of_arrangements` These are ordered selections without
56
repetition of k objects from a multiset S.
57
58
- Permutations of a multiset, :func:`permutations`,
59
:func:`permutations_iterator`, :func:`number_of_permutations`. A
60
permutation is a list that contains exactly the same elements but possibly
61
in different order.
62
63
**Partitions:**
64
65
- Partitions of a set, :func:`partitions_set`,
66
:func:`number_of_partitions_set`. An unordered partition
67
of set S is a set of pairwise disjoint nonempty sets with union S
68
and is represented by a sorted list of such sets.
69
70
- Partitions of an integer, :func:`Partitions`.
71
An unordered partition of n is an unordered sum
72
`n = p_1+p_2 +\ldots+ p_k` of positive integers and is
73
represented by the list `p = [p_1,p_2,\ldots,p_k]`, in
74
nonincreasing order, i.e., `p1\geq p_2 ...\geq p_k`.
75
76
- Ordered partitions of an integer,
77
:func:`ordered_partitions`,
78
:func:`number_of_ordered_partitions`. An ordered
79
partition of n is an ordered sum
80
`n = p_1+p_2 +\ldots+ p_k` of positive integers and is
81
represented by the list `p = [p_1,p_2,\ldots,p_k]`, in
82
nonincreasing order, i.e., `p1\geq p_2 ...\geq p_k`.
83
84
- :func:`partitions_greatest` implements a special type
85
of restricted partition.
86
87
- :func:`partitions_greatest_eq` is another type of
88
restricted partition.
89
90
- Tuples of partitions, :class:`PartitionTuples`. A `k`-tuple of partitions is
91
represented by a list of all `k`-tuples of partitions which together form a
92
partition of `n`.
93
94
**Related functions:**
95
96
- Bernoulli polynomials, :func:`bernoulli_polynomial`
97
98
**Implemented in other modules (listed for completeness):**
99
100
The ``sage.rings.arith`` module contains the following
101
combinatorial functions:
102
103
- binomial the binomial coefficient (wrapped from PARI)
104
105
- factorial (wrapped from PARI)
106
107
- partition (from the Python Cookbook) Generator of the list of
108
all the partitions of the integer `n`.
109
110
- :func:`number_of_partitions` (wrapped from PARI) the
111
*number* of partitions:
112
113
- :func:`falling_factorial` Definition: for integer
114
`a \ge 0` we have `x(x-1) \cdots (x-a+1)`. In all
115
other cases we use the GAMMA-function:
116
`\frac {\Gamma(x+1)} {\Gamma(x-a+1)}`.
117
118
- :func:`rising_factorial` Definition: for integer
119
`a \ge 0` we have `x(x+1) \cdots (x+a-1)`. In all
120
other cases we use the GAMMA-function:
121
`\frac {\Gamma(x+a)} {\Gamma(x)}`.
122
123
- gaussian_binomial the gaussian binomial
124
125
.. math::
126
127
\binom{n}{k}_q = \frac{(1-q^m)(1-q^{m-1})\cdots (1-q^{m-r+1})} {(1-q)(1-q^2)\cdots (1-q^r)}.
128
129
The ``sage.groups.perm_gps.permgroup_elements``
130
contains the following combinatorial functions:
131
132
133
- matrix method of PermutationGroupElement yielding the
134
permutation matrix of the group element.
135
136
.. TODO::
137
138
GUAVA commands:
139
* MOLS returns a list of n Mutually Orthogonal Latin Squares (MOLS).
140
* VandermondeMat
141
* GrayMat returns a list of all different vectors of length n over
142
the field F, using Gray ordering.
143
Not in GAP:
144
* Rencontres numbers
145
http://en.wikipedia.org/wiki/Rencontres_number
146
147
REFERENCES:
148
149
- http://en.wikipedia.org/wiki/Twelvefold_way (general reference)
150
151
AUTHORS:
152
153
- David Joyner (2006-07): initial implementation.
154
155
- William Stein (2006-07): editing of docs and code; many
156
optimizations, refinements, and bug fixes in corner cases
157
158
- David Joyner (2006-09): bug fix for combinations, added
159
permutations_iterator, combinations_iterator from Python Cookbook,
160
edited docs.
161
162
- David Joyner (2007-11): changed permutations, added hadamard_matrix
163
164
- Florent Hivert (2009-02): combinatorial class cleanup
165
166
- Fredrik Johansson (2010-07): fast implementation of ``stirling_number2``
167
168
- Punarbasu Purkayastha (2012-12): deprecate arrangements, combinations,
169
combinations_iterator, and clean up very old deprecated methods.
170
171
Functions and classes
172
---------------------
173
"""
174
175
#*****************************************************************************
176
# Copyright (C) 2006 David Joyner <[email protected]>,
177
# 2007 Mike Hansen <[email protected]>,
178
# 2006 William Stein <[email protected]>
179
#
180
# Distributed under the terms of the GNU General Public License (GPL)
181
#
182
# This code is distributed in the hope that it will be useful,
183
# but WITHOUT ANY WARRANTY; without even the implied warranty of
184
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
185
# General Public License for more details.
186
#
187
# The full text of the GPL is available at:
188
#
189
# http://www.gnu.org/licenses/
190
#*****************************************************************************
191
from sage.interfaces.all import gap, maxima
192
from sage.rings.all import QQ, ZZ, Integer
193
from sage.rings.arith import bernoulli, binomial
194
from sage.rings.polynomial.polynomial_element import Polynomial
195
from sage.misc.sage_eval import sage_eval
196
from sage.libs.all import pari
197
from sage.misc.prandom import randint
198
from sage.misc.misc import prod
199
from sage.structure.sage_object import SageObject
200
from sage.structure.parent import Parent
201
from sage.misc.lazy_attribute import lazy_attribute
202
from sage.misc.superseded import deprecation
203
from combinat_cython import _stirling_number2
204
######### combinatorial sequences
205
206
def bell_number(n, algorithm='dobinski', **options):
207
r"""
208
Return the `n`-th Bell number (the number of ways to partition a set
209
of n elements into pairwise disjoint nonempty subsets). If `n \leq 0`,
210
return `1`.
211
212
INPUT:
213
214
- ``n`` -- a positive integer
215
216
- ``algorithm`` -- (Default ``'dobinski'``) Can be any one of the
217
following:
218
219
- ``'dobinski'`` -- Use Dobinski's summation formula
220
(when `n < 200`, this just wraps GAP)
221
- ``'gap'`` -- Wrap GAP's ``Bell``
222
- ``'mpmath'`` -- Wrap mpmath's ``bell``
223
224
.. WARNING::
225
226
When using the mpmath algorithm to compute bell numbers and you specify
227
``prec``, it can return incorrect results due to low precision. See
228
the examples section.
229
230
Let `B_n` denote the `n`-th Bell number. Dobinski's formula is:
231
232
.. MATH::
233
234
B_n = e^{-1} \sum_{k=0}^{\infty} \frac{k^n}{k!}.
235
236
To show our implementation of Dobinski's method works, suppose that `n > 8`
237
and let `k_0` be the smallest integer for that `\frac{k_0^n}{k_0!} < 1`.
238
Note that `k_0 > n` and `k_0 \leq 2n` because we can prove that
239
`\frac{(2n)^n}{(2n)!} < 1` by Stirling.
240
241
Next if `k > k_0`, then we have `\frac{k^n}{k!} < \frac{1}{2^{k-k_0}}`, and
242
the proof is by induction. Let `c_k = \frac{k^n}{k!}`, if `k > n` then
243
244
.. MATH::
245
246
\frac{c_{k+1}}{c_k} = \frac{(1+k^{-1})^n}{k+1} < \frac{(1+n^{-1})^n}{n}
247
< \frac{4}{n} < \frac{1}{2}.
248
249
By using this, we can see that `\frac{c_k}{c_{k_0}} < \frac{1}{2^{k-k_0}}`
250
for `k > k_0 > n`. So summing this it gives that `\sum_{k=k_0+1}^{\infty}
251
\frac{k^n}{k!} < 1`, and hence
252
253
.. MATH::
254
255
B_n = e^{-1} \left( \sum_{k=0}^{k_0} \frac{k^n}{k!} + E_1 \right)
256
= e^{-1} \sum_{k=0}^{k_0} \frac{k^n}{k!} + E_2,
257
258
where `0 < E_1 < 1` and `0 < E_2 < e^{-1}`. Next we have:
259
260
.. MATH::
261
262
\sum_{k=0}^{k_0} \frac{k^n}{k!} = \sum_{k=0}^{k_0} n^{-2} \left\lfloor
263
\frac{n^2 k^n}{k!} \right\rfloor + \frac{E_3}{n^2}
264
265
where `0 \leq E_3 \leq k_0 + 1 \leq 2n + 1 \leq 3n`, so
266
267
.. MATH::
268
269
\sum_{k=0}^{k_0} \frac{k^n}{k!} = \sum_{k=0}{k_0} n^{-2} \left\lfloor
270
\frac{n^2 k^n}{k!} \right\rfloor + E_4,
271
272
where `0 \leq E_4 \leq \frac{3}{n}`. These two bounds gives:
273
274
.. MATH::
275
276
\begin{aligned}
277
B_n & = e^{-1} \sum_{k=0}^{k_0} n^{-2} \left\lfloor
278
\frac{n^2 k^n}{k!} \right\rfloor + e^{-1} E_4 + E_2 \\
279
& = e^{-1} \sum_{k=0}^{k_0} n^{-2} \left\lfloor \frac{n^2 k^n}{k!}
280
\right\rfloor + E_5
281
\end{aligned}
282
283
where
284
285
.. MATH::
286
287
0 \leq E_5 < e^{-1} + \frac{3e^{-1}}{n} \leq e^{-1} \left(1 +
288
\frac{3}{9}\right) < \frac{1}{2}.
289
290
Note `E_5` can be close to 0, so to avoid this, we subtract `\frac{1}{4}`
291
from the sum:
292
293
.. MATH::
294
295
\begin{aligned}
296
B_n & = e^{-1} \sum_{k=0}^{k_0} n^{-2} \left\lfloor \frac{n^2 k^n}{k!}
297
\right\rfloor - \frac{1}{4} + E, \\
298
B_n & = \left\lceil e^{-1} \sum_{k=0}^{k_0} n^{-2} \left\lfloor
299
\frac{n^2 k^n}{k!} \right\rfloor -1/4 \right\rceil
300
\end{aligned}
301
302
where `\frac{1}{4} \leq E < \frac{3}{4}`.
303
304
Lastly, to avoid the costly integer division by `k!`, in one step collect
305
more terms and do only one division, say collect 3 terms:
306
307
.. MATH::
308
309
\frac{k^n}{k!} + \frac{(k+1)^n}{(k+1)!} + \frac{(k+2)^n}{(k+2)!}
310
= \frac{k^n (k+1)(k+2) + (k+1)^n (k+2) + (k+2)^n}{(k+2)!}
311
312
using this all above error terms.
313
314
EXAMPLES::
315
316
sage: bell_number(10)
317
115975
318
sage: bell_number(2)
319
2
320
sage: bell_number(-10)
321
1
322
sage: bell_number(1)
323
1
324
sage: bell_number(1/3)
325
Traceback (most recent call last):
326
...
327
TypeError: no conversion of this rational to integer
328
329
When using the mpmath algorithm, we are required have mpmath's precision
330
set to at least `\log_2(B_n)` bits. If upon computing the Bell number the
331
first time, we deem the precision too low, we use our guess to
332
(temporarily) raise mpmath's precision and the Bell number is recomputed.
333
The result from GAP's bell number was checked agaist OEIS. ::
334
335
sage: k = bell_number(30, 'mpmath'); k
336
846749014511809332450147
337
sage: k == bell_number(30)
338
True
339
340
If you knows what precision is necessary before computing the Bell number,
341
you can use the ``prec`` option::
342
343
sage: k2 = bell_number(30, 'mpmath', prec=30); k2
344
846749014511809332450147
345
sage: k == k2
346
True
347
348
.. WARNING::
349
350
Running mpmath with the precision set too low can result in
351
incorrect results::
352
353
sage: k = bell_number(30, 'mpmath', prec=15); k
354
846749014511809388871680
355
sage: k == bell_number(30)
356
False
357
358
TESTS::
359
360
sage: all([bell_number(n) == bell_number(n,'gap') for n in range(200, 220)])
361
True
362
sage: all([bell_number(n) == bell_number(n,'mpmath', prec=500) for n in range(200, 220)])
363
True
364
365
AUTHORS:
366
367
- Robert Gerbicz
368
369
REFERENCES:
370
371
- :wikipedia:`Bell_number`
372
- http://fredrik-j.blogspot.com/2009/03/computing-generalized-bell-numbers.html
373
- http://mathworld.wolfram.com/DobinskisFormula.html
374
"""
375
if algorithm == 'mpmath':
376
from sage.libs.mpmath.all import bell, mp, mag
377
old_prec = mp.dps
378
if 'prec' in options:
379
mp.dps = options['prec']
380
ret = ZZ(int(bell(n)))
381
mp.dps = old_prec
382
return ret
383
ret_mp = bell(n)
384
p = mag(ret_mp) + 10
385
if p > mp.dps:
386
mp.dps = p
387
ret = ZZ(int(bell(n)))
388
mp.dps = old_prec
389
return ret
390
return ZZ(int(ret_mp))
391
if n < 200 or algorithm == 'gap':
392
return ZZ(gap.eval("Bell(%s)"%ZZ(n)))
393
from sage.functions.log import log
394
from sage.misc.functional import ceil, N, isqrt, exp as exp2
395
b, fact, k, n2, si = Integer(0), Integer(1), Integer(1), \
396
Integer(n)**2, isqrt(Integer(n)) // 2
397
while True:
398
mult, v = n2, Integer(0)
399
for i in range(si - 1, -1, -1):
400
v += mult * (k + i)**n
401
mult *= k + i
402
fact *= mult // n2
403
v //= fact
404
b += v
405
k += si
406
if v == 0:
407
break
408
return ZZ(ceil(N((b - n) / n2 * exp2(Integer(-1)) - 1 / 4, log(b, 2) + 3)))
409
410
def catalan_number(n):
411
r"""
412
Returns the n-th Catalan number
413
414
Catalan numbers: The `n`-th Catalan number is given
415
directly in terms of binomial coefficients by
416
417
.. MATH::
418
419
C_n = \frac{1}{n+1}{2n\choose n} = \frac{(2n)!}{(n+1)!\,n!}
420
\qquad\mbox{ for }\quad n\ge 0.
421
422
423
424
Consider the set `S = \{ 1, ..., n \}`. A noncrossing
425
partition of `S` is a partition in which no two blocks
426
"cross" each other, i.e., if a and b belong to one block and x and
427
y to another, they are not arranged in the order axby.
428
`C_n` is the number of noncrossing partitions of the set
429
`S`. There are many other interpretations (see
430
REFERENCES).
431
432
When `n=-1`, this function raises a ZeroDivisionError; for
433
other `n<0` it returns `0`.
434
435
INPUT:
436
437
- ``n`` - integer
438
439
OUTPUT: integer
440
441
442
443
EXAMPLES::
444
445
sage: [catalan_number(i) for i in range(7)]
446
[1, 1, 2, 5, 14, 42, 132]
447
sage: taylor((-1/2)*sqrt(1 - 4*x^2), x, 0, 15)
448
132*x^14 + 42*x^12 + 14*x^10 + 5*x^8 + 2*x^6 + x^4 + x^2 - 1/2
449
sage: [catalan_number(i) for i in range(-7,7) if i != -1]
450
[0, 0, 0, 0, 0, 0, 1, 1, 2, 5, 14, 42, 132]
451
sage: catalan_number(-1)
452
Traceback (most recent call last):
453
...
454
ZeroDivisionError
455
sage: [catalan_number(n).mod(2) for n in range(16)]
456
[1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1]
457
458
REFERENCES:
459
460
- http://en.wikipedia.org/wiki/Catalan_number
461
462
- http://www-history.mcs.st-andrews.ac.uk/~history/Miscellaneous/CatalanNumbers/catalan.html
463
"""
464
from sage.rings.arith import binomial
465
n = ZZ(n)
466
return binomial(2*n,n).divide_knowing_divisible_by(n+1)
467
468
def euler_number(n):
469
"""
470
Returns the n-th Euler number
471
472
IMPLEMENTATION: Wraps Maxima's euler.
473
474
EXAMPLES::
475
476
sage: [euler_number(i) for i in range(10)]
477
[1, 0, -1, 0, 5, 0, -61, 0, 1385, 0]
478
sage: maxima.eval("taylor (2/(exp(x)+exp(-x)), x, 0, 10)")
479
'1-x^2/2+5*x^4/24-61*x^6/720+277*x^8/8064-50521*x^10/3628800'
480
sage: [euler_number(i)/factorial(i) for i in range(11)]
481
[1, 0, -1/2, 0, 5/24, 0, -61/720, 0, 277/8064, 0, -50521/3628800]
482
sage: euler_number(-1)
483
Traceback (most recent call last):
484
...
485
ValueError: n (=-1) must be a nonnegative integer
486
487
REFERENCES:
488
489
- http://en.wikipedia.org/wiki/Euler_number
490
"""
491
n = ZZ(n)
492
if n < 0:
493
raise ValueError, "n (=%s) must be a nonnegative integer"%n
494
return ZZ(maxima.eval("euler(%s)"%n))
495
496
def fibonacci(n, algorithm="pari"):
497
"""
498
Returns the n-th Fibonacci number. The Fibonacci sequence
499
`F_n` is defined by the initial conditions
500
`F_1=F_2=1` and the recurrence relation
501
`F_{n+2} = F_{n+1} + F_n`. For negative `n` we
502
define `F_n = (-1)^{n+1}F_{-n}`, which is consistent with
503
the recurrence relation.
504
505
INPUT:
506
507
508
- ``algorithm`` - string:
509
510
- ``"pari"`` - (default) - use the PARI C library's
511
fibo function.
512
513
- ``"gap"`` - use GAP's Fibonacci function
514
515
516
.. note::
517
518
PARI is tens to hundreds of times faster than GAP here;
519
moreover, PARI works for every large input whereas GAP doesn't.
520
521
EXAMPLES::
522
523
sage: fibonacci(10)
524
55
525
sage: fibonacci(10, algorithm='gap')
526
55
527
528
::
529
530
sage: fibonacci(-100)
531
-354224848179261915075
532
sage: fibonacci(100)
533
354224848179261915075
534
535
::
536
537
sage: fibonacci(0)
538
0
539
sage: fibonacci(1/2)
540
Traceback (most recent call last):
541
...
542
TypeError: no conversion of this rational to integer
543
"""
544
n = ZZ(n)
545
if algorithm == 'pari':
546
return ZZ(pari(n).fibonacci())
547
elif algorithm == 'gap':
548
return ZZ(gap.eval("Fibonacci(%s)"%n))
549
else:
550
raise ValueError, "no algorithm %s"%algorithm
551
552
def lucas_number1(n,P,Q):
553
"""
554
Returns the n-th Lucas number "of the first kind" (this is not
555
standard terminology). The Lucas sequence `L^{(1)}_n` is
556
defined by the initial conditions `L^{(1)}_1=0`,
557
`L^{(1)}_2=1` and the recurrence relation
558
`L^{(1)}_{n+2} = P*L^{(1)}_{n+1} - Q*L^{(1)}_n`.
559
560
Wraps GAP's Lucas(...)[1].
561
562
P=1, Q=-1 gives the Fibonacci sequence.
563
564
INPUT:
565
566
567
- ``n`` - integer
568
569
- ``P, Q`` - integer or rational numbers
570
571
572
OUTPUT: integer or rational number
573
574
EXAMPLES::
575
576
sage: lucas_number1(5,1,-1)
577
5
578
sage: lucas_number1(6,1,-1)
579
8
580
sage: lucas_number1(7,1,-1)
581
13
582
sage: lucas_number1(7,1,-2)
583
43
584
585
::
586
587
sage: lucas_number1(5,2,3/5)
588
229/25
589
sage: lucas_number1(5,2,1.5)
590
Traceback (most recent call last):
591
...
592
TypeError: no canonical coercion from Real Field with 53 bits of precision to Rational Field
593
594
There was a conjecture that the sequence `L_n` defined by
595
`L_{n+2} = L_{n+1} + L_n`, `L_1=1`,
596
`L_2=3`, has the property that `n` prime implies
597
that `L_n` is prime.
598
599
::
600
601
sage: lucas = lambda n : Integer((5/2)*lucas_number1(n,1,-1)+(1/2)*lucas_number2(n,1,-1))
602
sage: [[lucas(n),is_prime(lucas(n)),n+1,is_prime(n+1)] for n in range(15)]
603
[[1, False, 1, False],
604
[3, True, 2, True],
605
[4, False, 3, True],
606
[7, True, 4, False],
607
[11, True, 5, True],
608
[18, False, 6, False],
609
[29, True, 7, True],
610
[47, True, 8, False],
611
[76, False, 9, False],
612
[123, False, 10, False],
613
[199, True, 11, True],
614
[322, False, 12, False],
615
[521, True, 13, True],
616
[843, False, 14, False],
617
[1364, False, 15, False]]
618
619
Can you use Sage to find a counterexample to the conjecture?
620
"""
621
ans=gap.eval("Lucas(%s,%s,%s)[1]"%(QQ._coerce_(P),QQ._coerce_(Q),ZZ(n)))
622
return sage_eval(ans)
623
624
def lucas_number2(n,P,Q):
625
r"""
626
Returns the n-th Lucas number "of the second kind" (this is not
627
standard terminology). The Lucas sequence `L^{(2)}_n` is
628
defined by the initial conditions `L^{(2)}_1=2`,
629
`L^{(2)}_2=P` and the recurrence relation
630
`L^{(2)}_{n+2} = P*L^{(2)}_{n+1} - Q*L^{(2)}_n`.
631
632
Wraps GAP's Lucas(...)[2].
633
634
INPUT:
635
636
637
- ``n`` - integer
638
639
- ``P, Q`` - integer or rational numbers
640
641
642
OUTPUT: integer or rational number
643
644
EXAMPLES::
645
646
sage: [lucas_number2(i,1,-1) for i in range(10)]
647
[2, 1, 3, 4, 7, 11, 18, 29, 47, 76]
648
sage: [fibonacci(i-1)+fibonacci(i+1) for i in range(10)]
649
[2, 1, 3, 4, 7, 11, 18, 29, 47, 76]
650
651
::
652
653
sage: n = lucas_number2(5,2,3); n
654
2
655
sage: type(n)
656
<type 'sage.rings.integer.Integer'>
657
sage: n = lucas_number2(5,2,-3/9); n
658
418/9
659
sage: type(n)
660
<type 'sage.rings.rational.Rational'>
661
662
The case P=1, Q=-1 is the Lucas sequence in Brualdi's Introductory
663
Combinatorics, 4th ed., Prentice-Hall, 2004::
664
665
sage: [lucas_number2(n,1,-1) for n in range(10)]
666
[2, 1, 3, 4, 7, 11, 18, 29, 47, 76]
667
"""
668
ans=gap.eval("Lucas(%s,%s,%s)[2]"%(QQ._coerce_(P),QQ._coerce_(Q),ZZ(n)))
669
return sage_eval(ans)
670
671
def stirling_number1(n,k):
672
"""
673
Returns the n-th Stilling number `S_1(n,k)` of the first
674
kind (the number of permutations of n points with k cycles). Wraps
675
GAP's Stirling1.
676
677
EXAMPLES::
678
679
sage: stirling_number1(3,2)
680
3
681
sage: stirling_number1(5,2)
682
50
683
sage: 9*stirling_number1(9,5)+stirling_number1(9,4)
684
269325
685
sage: stirling_number1(10,5)
686
269325
687
688
Indeed, `S_1(n,k) = S_1(n-1,k-1) + (n-1)S_1(n-1,k)`.
689
"""
690
return ZZ(gap.eval("Stirling1(%s,%s)"%(ZZ(n),ZZ(k))))
691
692
def stirling_number2(n, k, algorithm=None):
693
"""
694
Returns the n-th Stirling number `S_2(n,k)` of the second
695
kind (the number of ways to partition a set of n elements into k
696
pairwise disjoint nonempty subsets). (The n-th Bell number is the
697
sum of the `S_2(n,k)`'s, `k=0,...,n`.)
698
699
INPUT:
700
701
* ``n`` - nonnegative machine-size integer
702
* ``k`` - nonnegative machine-size integer
703
* ``algorithm``:
704
705
* None (default) - use native implementation
706
* ``"maxima"`` - use Maxima's stirling2 function
707
* ``"gap"`` - use GAP's Stirling2 function
708
709
EXAMPLES:
710
711
Print a table of the first several Stirling numbers of the second kind::
712
713
sage: for n in range(10):
714
... for k in range(10):
715
... print str(stirling_number2(n,k)).rjust(k and 6),
716
... print
717
...
718
1 0 0 0 0 0 0 0 0 0
719
0 1 0 0 0 0 0 0 0 0
720
0 1 1 0 0 0 0 0 0 0
721
0 1 3 1 0 0 0 0 0 0
722
0 1 7 6 1 0 0 0 0 0
723
0 1 15 25 10 1 0 0 0 0
724
0 1 31 90 65 15 1 0 0 0
725
0 1 63 301 350 140 21 1 0 0
726
0 1 127 966 1701 1050 266 28 1 0
727
0 1 255 3025 7770 6951 2646 462 36 1
728
729
Stirling numbers satisfy `S_2(n,k) = S_2(n-1,k-1) + kS_2(n-1,k)`::
730
731
sage: 5*stirling_number2(9,5) + stirling_number2(9,4)
732
42525
733
sage: stirling_number2(10,5)
734
42525
735
736
TESTS::
737
738
sage: stirling_number2(500,501)
739
0
740
sage: stirling_number2(500,500)
741
1
742
sage: stirling_number2(500,499)
743
124750
744
sage: stirling_number2(500,498)
745
7739801875
746
sage: stirling_number2(500,497)
747
318420320812125
748
sage: stirling_number2(500,0)
749
0
750
sage: stirling_number2(500,1)
751
1
752
sage: stirling_number2(500,2)
753
1636695303948070935006594848413799576108321023021532394741645684048066898202337277441635046162952078575443342063780035504608628272942696526664263794687
754
sage: stirling_number2(500,3)
755
6060048632644989473730877846590553186337230837666937173391005972096766698597315914033083073801260849147094943827552228825899880265145822824770663507076289563105426204030498939974727520682393424986701281896187487826395121635163301632473646
756
sage: stirling_number2(500,30)
757
13707767141249454929449108424328432845001327479099713037876832759323918134840537229737624018908470350134593241314462032607787062188356702932169472820344473069479621239187226765307960899083230982112046605340713218483809366970996051181537181362810003701997334445181840924364501502386001705718466534614548056445414149016614254231944272872440803657763210998284198037504154374028831561296154209804833852506425742041757849726214683321363035774104866182331315066421119788248419742922490386531970053376982090046434022248364782970506521655684518998083846899028416459701847828711541840099891244700173707021989771147674432503879702222276268661726508226951587152781439224383339847027542755222936463527771486827849728880
758
sage: stirling_number2(500,31)
759
5832088795102666690960147007601603328246123996896731854823915012140005028360632199516298102446004084519955789799364757997824296415814582277055514048635928623579397278336292312275467402957402880590492241647229295113001728653772550743446401631832152281610081188041624848850056657889275564834450136561842528589000245319433225808712628826136700651842562516991245851618481622296716433577650218003181535097954294609857923077238362717189185577756446945178490324413383417876364657995818830270448350765700419876347023578011403646501685001538551891100379932684279287699677429566813471166558163301352211170677774072447414719380996777162087158124939742564291760392354506347716119002497998082844612434332155632097581510486912
760
sage: n = stirling_number2(20,11)
761
sage: n
762
1900842429486
763
sage: type(n)
764
<type 'sage.rings.integer.Integer'>
765
sage: n = stirling_number2(20,11,algorithm='gap')
766
sage: n
767
1900842429486
768
sage: type(n)
769
<type 'sage.rings.integer.Integer'>
770
sage: n = stirling_number2(20,11,algorithm='maxima')
771
sage: n
772
1900842429486
773
sage: type(n)
774
<type 'sage.rings.integer.Integer'>
775
776
Sage's implementation splitting the computation of the Stirling
777
numbers of the second kind in two cases according to `n`, let us
778
check the result it gives agree with both maxima and gap.
779
780
For `n<200`::
781
782
sage: for n in Subsets(range(100,200), 5).random_element():
783
... for k in Subsets(range(n), 5).random_element():
784
... s_sage = stirling_number2(n,k)
785
... s_maxima = stirling_number2(n,k, algorithm = "maxima")
786
... s_gap = stirling_number2(n,k, algorithm = "gap")
787
... if not (s_sage == s_maxima and s_sage == s_gap):
788
... print "Error with n<200"
789
790
For `n\geq 200`::
791
792
sage: for n in Subsets(range(200,300), 5).random_element():
793
... for k in Subsets(range(n), 5).random_element():
794
... s_sage = stirling_number2(n,k)
795
... s_maxima = stirling_number2(n,k, algorithm = "maxima")
796
... s_gap = stirling_number2(n,k, algorithm = "gap")
797
... if not (s_sage == s_maxima and s_sage == s_gap):
798
... print "Error with n<200"
799
800
801
TESTS:
802
803
Checking an exception is raised whenever a wrong value is given
804
for ``algorithm``::
805
806
sage: s_sage = stirling_number2(50,3, algorithm = "CloudReading")
807
Traceback (most recent call last):
808
...
809
ValueError: unknown algorithm: CloudReading
810
"""
811
if algorithm is None:
812
return _stirling_number2(n, k)
813
elif algorithm == 'gap':
814
return ZZ(gap.eval("Stirling2(%s,%s)"%(ZZ(n),ZZ(k))))
815
elif algorithm == 'maxima':
816
return ZZ(maxima.eval("stirling2(%s,%s)"%(ZZ(n),ZZ(k))))
817
else:
818
raise ValueError("unknown algorithm: %s" % algorithm)
819
820
class CombinatorialObject(SageObject):
821
def __init__(self, l):
822
"""
823
CombinatorialObject provides a thin wrapper around a list. The main
824
differences are that __setitem__ is disabled so that
825
CombinatorialObjects are shallowly immutable, and the intention is
826
that they are semantically immutable.
827
828
Because of this, CombinatorialObjects provide a __hash__
829
function which computes the hash of the string representation of a
830
list and the hash of its parent's class. Thus, each
831
CombinatorialObject should have a unique string representation.
832
833
INPUT:
834
835
- ``l`` - a list or any object that can be convert to a list by
836
``list``
837
838
EXAMPLES::
839
840
sage: c = CombinatorialObject([1,2,3])
841
sage: c == loads(dumps(c))
842
True
843
sage: c._list
844
[1, 2, 3]
845
sage: c._hash is None
846
True
847
"""
848
if isinstance(l, list):
849
self._list = l
850
else:
851
self._list = list(l)
852
self._hash = None
853
854
def __str__(self):
855
"""
856
EXAMPLES::
857
858
sage: c = CombinatorialObject([1,2,3])
859
sage: str(c)
860
'[1, 2, 3]'
861
"""
862
return str(self._list)
863
864
def __cmp__(self, other):
865
"""
866
EXAMPLES::
867
868
sage: c = CombinatorialObject([1,2,3])
869
sage: d = CombinatorialObject([3,2,1])
870
sage: cmp(c, d)
871
-1
872
sage: cmp(d, c)
873
1
874
sage: cmp(c, c)
875
0
876
877
Check that :trac:`14065` is fixed::
878
879
sage: from sage.structure.element import Element
880
sage: class Foo(CombinatorialObject, Element): pass
881
sage: L = [Foo([4-i]) for i in range(4)]; L
882
[[4], [3], [2], [1]]
883
sage: sorted(L, cmp)
884
[[1], [2], [3], [4]]
885
sage: f = Foo([4])
886
sage: f == None
887
False
888
sage: f != None
889
True
890
891
.. WARNING::
892
893
:class:`CombinatorialObject` must come **before** :class:`Element`
894
for this to work becuase :class:`Element` is ahead of
895
:class:`CombinatorialObject` in the MRO (method resolution
896
order)::
897
898
sage: from sage.structure.element import Element
899
sage: class Bar(Element, CombinatorialObject):
900
... def __init__(self, l):
901
... CombinatorialObject.__init__(self, l)
902
...
903
sage: L = [Bar([4-i]) for i in range(4)]
904
sage: sorted(L, cmp)
905
Traceback (most recent call last):
906
...
907
NotImplementedError: BUG: sort algorithm for elements of 'None' not implemented
908
"""
909
if isinstance(other, CombinatorialObject):
910
return cmp(self._list, other._list)
911
else:
912
return cmp(self._list, other)
913
914
def _repr_(self):
915
"""
916
EXAMPLES::
917
918
sage: c = CombinatorialObject([1,2,3])
919
sage: c.__repr__()
920
'[1, 2, 3]'
921
"""
922
return self._list.__repr__()
923
924
def __eq__(self, other):
925
"""
926
EXAMPLES::
927
928
sage: c = CombinatorialObject([1,2,3])
929
sage: d = CombinatorialObject([2,3,4])
930
sage: c == [1,2,3]
931
True
932
sage: c == [2,3,4]
933
False
934
sage: c == d
935
False
936
"""
937
938
if isinstance(other, CombinatorialObject):
939
return self._list.__eq__(other._list)
940
else:
941
return self._list.__eq__(other)
942
943
def __lt__(self, other):
944
"""
945
EXAMPLES::
946
947
sage: c = CombinatorialObject([1,2,3])
948
sage: d = CombinatorialObject([2,3,4])
949
sage: c < d
950
True
951
sage: c < [2,3,4]
952
True
953
"""
954
955
if isinstance(other, CombinatorialObject):
956
return self._list.__lt__(other._list)
957
else:
958
return self._list.__lt__(other)
959
960
def __le__(self, other):
961
"""
962
EXAMPLES::
963
964
sage: c = CombinatorialObject([1,2,3])
965
sage: d = CombinatorialObject([2,3,4])
966
sage: c <= c
967
True
968
sage: c <= d
969
True
970
sage: c <= [1,2,3]
971
True
972
"""
973
if isinstance(other, CombinatorialObject):
974
return self._list.__le__(other._list)
975
else:
976
return self._list.__le__(other)
977
978
def __gt__(self, other):
979
"""
980
EXAMPLES::
981
982
sage: c = CombinatorialObject([1,2,3])
983
sage: d = CombinatorialObject([2,3,4])
984
sage: c > c
985
False
986
sage: c > d
987
False
988
sage: c > [1,2,3]
989
False
990
"""
991
if isinstance(other, CombinatorialObject):
992
return self._list.__gt__(other._list)
993
else:
994
return self._list.__gt__(other)
995
996
def __ge__(self, other):
997
"""
998
EXAMPLES::
999
1000
sage: c = CombinatorialObject([1,2,3])
1001
sage: d = CombinatorialObject([2,3,4])
1002
sage: c >= c
1003
True
1004
sage: c >= d
1005
False
1006
sage: c >= [1,2,3]
1007
True
1008
"""
1009
if isinstance(other, CombinatorialObject):
1010
return self._list.__ge__(other._list)
1011
else:
1012
return self._list.__ge__(other)
1013
1014
def __ne__(self, other):
1015
"""
1016
EXAMPLES::
1017
1018
sage: c = CombinatorialObject([1,2,3])
1019
sage: d = CombinatorialObject([2,3,4])
1020
sage: c != c
1021
False
1022
sage: c != d
1023
True
1024
sage: c != [1,2,3]
1025
False
1026
"""
1027
if isinstance(other, CombinatorialObject):
1028
return self._list.__ne__(other._list)
1029
else:
1030
return self._list.__ne__(other)
1031
1032
def __add__(self, other):
1033
"""
1034
EXAMPLES::
1035
1036
sage: c = CombinatorialObject([1,2,3])
1037
sage: c + [4]
1038
[1, 2, 3, 4]
1039
sage: type(_)
1040
<type 'list'>
1041
"""
1042
return self._list + other
1043
1044
def __hash__(self):
1045
"""
1046
Computes the hash of self by computing the hash of the string
1047
representation of self._list. The hash is cached and stored in
1048
self._hash.
1049
1050
EXAMPLES::
1051
1052
sage: c = CombinatorialObject([1,2,3])
1053
sage: c._hash is None
1054
True
1055
sage: hash(c) #random
1056
1335416675971793195
1057
sage: c._hash #random
1058
1335416675971793195
1059
"""
1060
if self._hash is None:
1061
self._hash = str(self._list).__hash__()
1062
return self._hash
1063
1064
def __nonzero__(self):
1065
"""
1066
Return ``True`` if ``self`` is non-zero.
1067
1068
We consider a list to be zero if it has length zero.
1069
1070
TESTS::
1071
1072
sage: c = CombinatorialObject([1,2,3])
1073
sage: not c
1074
False
1075
sage: c = CombinatorialObject([])
1076
sage: not c
1077
True
1078
1079
Check that :trac:`14065` is fixed::
1080
1081
sage: from sage.structure.element import Element
1082
sage: class Foo(CombinatorialObject, Element): pass
1083
...
1084
sage: f = Foo([4])
1085
sage: not f
1086
False
1087
sage: f = Foo([])
1088
sage: not f
1089
True
1090
1091
.. WARNING::
1092
1093
:class:`CombinatorialObject` must come **before** :class:`Element`
1094
for this to work becuase :class:`Element` is ahead of
1095
:class:`CombinatorialObject` in the MRO (method resolution
1096
order)::
1097
1098
sage: from sage.structure.element import Element
1099
sage: class Bar(Element, CombinatorialObject):
1100
... def __init__(self, l):
1101
... CombinatorialObject.__init__(self, l)
1102
...
1103
sage: b = Bar([4])
1104
sage: not b
1105
Traceback (most recent call last):
1106
...
1107
AttributeError: 'NoneType' object has no attribute 'zero_element'
1108
"""
1109
return bool(self._list)
1110
1111
def __len__(self):
1112
"""
1113
EXAMPLES::
1114
1115
sage: c = CombinatorialObject([1,2,3])
1116
sage: len(c)
1117
3
1118
sage: c.__len__()
1119
3
1120
"""
1121
return self._list.__len__()
1122
1123
def __getitem__(self, key):
1124
"""
1125
EXAMPLES::
1126
1127
sage: c = CombinatorialObject([1,2,3])
1128
sage: c[0]
1129
1
1130
sage: c[1:]
1131
[2, 3]
1132
sage: type(_)
1133
<type 'list'>
1134
"""
1135
return self._list.__getitem__(key)
1136
1137
def __iter__(self):
1138
"""
1139
EXAMPLES::
1140
1141
sage: c = CombinatorialObject([1,2,3])
1142
sage: list(iter(c))
1143
[1, 2, 3]
1144
"""
1145
return self._list.__iter__()
1146
1147
def __contains__(self, item):
1148
"""
1149
EXAMPLES::
1150
1151
sage: c = CombinatorialObject([1,2,3])
1152
sage: 1 in c
1153
True
1154
sage: 5 in c
1155
False
1156
"""
1157
return self._list.__contains__(item)
1158
1159
1160
def index(self, key):
1161
"""
1162
EXAMPLES::
1163
1164
sage: c = CombinatorialObject([1,2,3])
1165
sage: c.index(1)
1166
0
1167
sage: c.index(3)
1168
2
1169
"""
1170
return self._list.index(key)
1171
1172
1173
from sage.misc.classcall_metaclass import ClasscallMetaclass
1174
from sage.categories.enumerated_sets import EnumeratedSets
1175
class CombinatorialClass(Parent):
1176
"""
1177
This class is deprecated, and will disappear as soon as all derived
1178
classes in Sage's library will have been fixed. Please derive
1179
directly from Parent and use the category :class:`EnumeratedSets`,
1180
:class:`FiniteEnumeratedSets`, or :class:`InfiniteEnumeratedSets`, as
1181
appropriate.
1182
1183
For examples, see::
1184
1185
sage: FiniteEnumeratedSets().example()
1186
An example of a finite enumerated set: {1,2,3}
1187
sage: InfiniteEnumeratedSets().example()
1188
An example of an infinite enumerated set: the non negative integers
1189
"""
1190
__metaclass__ = ClasscallMetaclass
1191
1192
def __init__(self, category = None, *keys, **opts):
1193
"""
1194
TESTS::
1195
1196
sage: C = sage.combinat.combinat.CombinatorialClass()
1197
sage: C.category()
1198
Category of enumerated sets
1199
sage: C.__class__
1200
<class 'sage.combinat.combinat.CombinatorialClass_with_category'>
1201
sage: isinstance(C, Parent)
1202
True
1203
sage: C = sage.combinat.combinat.CombinatorialClass(category = FiniteEnumeratedSets())
1204
sage: C.category()
1205
Category of finite enumerated sets
1206
"""
1207
Parent.__init__(self, category = EnumeratedSets().or_subcategory(category))
1208
1209
1210
def __len__(self):
1211
"""
1212
__len__ has been removed ! to get the number of element in a
1213
combinatorial class, use .cardinality instead.
1214
1215
1216
TEST::
1217
1218
sage: class C(CombinatorialClass):
1219
... def __iter__(self):
1220
... return iter([1,2,3])
1221
...
1222
sage: len(C())
1223
Traceback (most recent call last):
1224
...
1225
AttributeError: __len__ has been removed; use .cardinality() instead
1226
"""
1227
raise AttributeError, "__len__ has been removed; use .cardinality() instead"
1228
1229
def is_finite(self):
1230
"""
1231
Returns whether self is finite or not.
1232
1233
EXAMPLES::
1234
1235
sage: Partitions(5).is_finite()
1236
True
1237
sage: Permutations().is_finite()
1238
False
1239
"""
1240
from sage.rings.all import infinity
1241
return self.cardinality() != infinity
1242
1243
def __getitem__(self, i):
1244
"""
1245
Returns the combinatorial object of rank i.
1246
1247
EXAMPLES::
1248
1249
sage: class C(CombinatorialClass):
1250
... def __iter__(self):
1251
... return iter([1,2,3])
1252
...
1253
sage: c = C()
1254
sage: c[0]
1255
1
1256
sage: c[2]
1257
3
1258
sage: c[4]
1259
Traceback (most recent call last):
1260
...
1261
ValueError: the value must be between 0 and 2 inclusive
1262
"""
1263
return self.unrank(i)
1264
1265
def __str__(self):
1266
"""
1267
Returns a string representation of self.
1268
1269
EXAMPLES::
1270
1271
sage: str(Partitions(5))
1272
'Partitions of the integer 5'
1273
"""
1274
return self.__repr__()
1275
1276
def _repr_(self):
1277
"""
1278
EXAMPLES::
1279
1280
sage: repr(Partitions(5)) # indirect doctest
1281
'Partitions of the integer 5'
1282
"""
1283
if hasattr(self, '_name') and self._name:
1284
return self._name
1285
else:
1286
return "Combinatorial Class -- REDEFINE ME!"
1287
1288
def __contains__(self, x):
1289
"""
1290
Tests whether or not the combinatorial class contains the object x.
1291
This raises a NotImplementedError as a default since _all_
1292
subclasses of CombinatorialClass should override this.
1293
1294
Note that we could replace this with a default implementation that
1295
just iterates through the elements of the combinatorial class and
1296
checks for equality. However, since we use __contains__ for
1297
type checking, this operation should be cheap and should be
1298
implemented manually for each combinatorial class.
1299
1300
EXAMPLES::
1301
1302
sage: C = CombinatorialClass()
1303
sage: x in C
1304
Traceback (most recent call last):
1305
...
1306
NotImplementedError
1307
"""
1308
raise NotImplementedError
1309
1310
def __cmp__(self, x):
1311
"""
1312
Compares two different combinatorial classes. For now, the
1313
comparison is done just on their repr's.
1314
1315
EXAMPLES::
1316
1317
sage: p5 = Partitions(5)
1318
sage: p6 = Partitions(6)
1319
sage: repr(p5) == repr(p6)
1320
False
1321
sage: p5 == p6
1322
False
1323
"""
1324
return cmp(repr(self), repr(x))
1325
1326
def __cardinality_from_iterator(self):
1327
"""
1328
Default implementation of cardinality which just goes through the iterator
1329
of the combinatorial class to count the number of objects.
1330
1331
EXAMPLES::
1332
1333
sage: class C(CombinatorialClass):
1334
... def __iter__(self):
1335
... return iter([1,2,3])
1336
...
1337
sage: C().cardinality() #indirect doctest
1338
3
1339
"""
1340
c = Integer(0)
1341
one = Integer(1)
1342
for _ in self:
1343
c += one
1344
return c
1345
cardinality = __cardinality_from_iterator
1346
1347
# __call__, element_class, and _element_constructor_ are poor
1348
# man's versions of those from Parent. This is for transition,
1349
# until all combinatorial classes are proper parents (in Parent)
1350
# and use coercion, etcc
1351
1352
def __call__(self, x):
1353
"""
1354
Returns x as an element of the combinatorial class's object class.
1355
1356
EXAMPLES::
1357
1358
sage: p5 = Partitions(5)
1359
sage: a = [2,2,1]
1360
sage: type(a)
1361
<type 'list'>
1362
sage: a = p5(a)
1363
sage: type(a)
1364
<class 'sage.combinat.partition.Partitions_n_with_category.element_class'>
1365
sage: p5([2,1])
1366
Traceback (most recent call last):
1367
...
1368
ValueError: [2, 1] is not an element of Partitions of the integer 5
1369
"""
1370
if x in self:
1371
return self._element_constructor_(x)
1372
else:
1373
raise ValueError, "%s not in %s"%(x, self)
1374
1375
Element = CombinatorialObject # mostly for backward compatibility
1376
@lazy_attribute
1377
def element_class(self):
1378
"""
1379
This function is a temporary helper so that a CombinatorialClass
1380
behaves as a parent for creating elements. This will disappear when
1381
combinatorial classes will be turned into actual parents (in the
1382
category EnumeratedSets).
1383
1384
TESTS::
1385
1386
sage: P5 = Partitions(5)
1387
sage: P5.element_class
1388
<class 'sage.combinat.partition.Partitions_n_with_category.element_class'>
1389
"""
1390
# assert not isinstance(self, Parent) # Raises an alert if we override the proper definition from Parent
1391
if hasattr(self, "object_class"):
1392
deprecation(5891, "Using object_class for specifying the class "
1393
"of the elements of a combinatorial class is "
1394
"deprecated. Please use Element instead.")
1395
return self.Element
1396
1397
def _element_constructor_(self, x):
1398
"""
1399
This function is a temporary helper so that a CombinatorialClass
1400
behaves as a parent for creating elements. This will disappear when
1401
combinatorial classes will be turned into actual parents (in the
1402
category EnumeratedSets).
1403
1404
TESTS::
1405
1406
sage: P5 = Partitions(5)
1407
sage: p = P5([3,2]) # indirect doctest
1408
sage: type(p)
1409
<class 'sage.combinat.partition.Partitions_n_with_category.element_class'>
1410
"""
1411
# assert not isinstance(self, Parent) # Raises an alert if we override the proper definition from Parent
1412
return self.element_class(x)
1413
1414
def __list_from_iterator(self):
1415
"""
1416
The default implementation of list which builds the list from the
1417
iterator.
1418
1419
EXAMPLES::
1420
1421
sage: class C(CombinatorialClass):
1422
... def __iter__(self):
1423
... return iter([1,2,3])
1424
...
1425
sage: C().list() #indirect doctest
1426
[1, 2, 3]
1427
"""
1428
return [x for x in self]
1429
1430
#Set list to the default implementation
1431
list = __list_from_iterator
1432
1433
#Set the default object class to be CombinatorialObject
1434
Element = CombinatorialObject
1435
1436
def __iterator_from_next(self):
1437
"""
1438
An iterator to use when .first() and .next() are provided.
1439
1440
EXAMPLES::
1441
1442
sage: C = CombinatorialClass()
1443
sage: C.first = lambda: 0
1444
sage: C.next = lambda c: c+1
1445
sage: it = iter(C) # indirect doctest
1446
sage: [it.next() for _ in range(4)]
1447
[0, 1, 2, 3]
1448
"""
1449
f = self.first()
1450
yield f
1451
while True:
1452
try:
1453
f = self.next(f)
1454
except (TypeError, ValueError ):
1455
break
1456
1457
if f is None or f is False :
1458
break
1459
else:
1460
yield f
1461
1462
def __iterator_from_previous(self):
1463
"""
1464
An iterator to use when .last() and .previous() are provided. Note
1465
that this requires the combinatorial class to be finite. It is not
1466
recommended to implement combinatorial classes using last and
1467
previous.
1468
1469
EXAMPLES::
1470
1471
sage: C = CombinatorialClass()
1472
sage: C.last = lambda: 4
1473
sage: def prev(c):
1474
... if c <= 1:
1475
... return None
1476
... else:
1477
... return c-1
1478
...
1479
sage: C.previous = prev
1480
sage: it = iter(C) # indirect doctest
1481
sage: [it.next() for _ in range(4)]
1482
[1, 2, 3, 4]
1483
"""
1484
l = self.last()
1485
li = [l]
1486
while True:
1487
try:
1488
l = self.previous(l)
1489
except (TypeError, ValueError):
1490
break
1491
1492
if l == None:
1493
break
1494
else:
1495
li.append(l)
1496
return reversed(li)
1497
1498
def __iterator_from_unrank(self):
1499
"""
1500
An iterator to use when .unrank() is provided.
1501
1502
EXAMPLES::
1503
1504
sage: C = CombinatorialClass()
1505
sage: l = [1,2,3]
1506
sage: C.unrank = lambda c: l[c]
1507
sage: list(C) # indirect doctest
1508
[1, 2, 3]
1509
"""
1510
r = 0
1511
u = self.unrank(r)
1512
yield u
1513
while True:
1514
r += 1
1515
try:
1516
u = self.unrank(r)
1517
except (TypeError, ValueError, IndexError):
1518
break
1519
1520
if u == None:
1521
break
1522
else:
1523
yield u
1524
1525
def __iterator_from_list(self):
1526
"""
1527
An iterator to use when .list() is provided()
1528
1529
EXAMPLES::
1530
1531
sage: C = CombinatorialClass()
1532
sage: C.list = lambda: [1, 2, 3]
1533
sage: list(C) # indirect doctest
1534
[1, 2, 3]
1535
"""
1536
for x in self.list():
1537
yield x
1538
1539
def __iter__(self):
1540
"""
1541
Allows the combinatorial class to be treated as an iterator. Default
1542
implementation.
1543
1544
EXAMPLES::
1545
1546
sage: p5 = Partitions(5)
1547
sage: [i for i in p5]
1548
[[5], [4, 1], [3, 2], [3, 1, 1], [2, 2, 1], [2, 1, 1, 1], [1, 1, 1, 1, 1]]
1549
sage: C = CombinatorialClass()
1550
sage: iter(C)
1551
Traceback (most recent call last):
1552
...
1553
NotImplementedError: iterator called but not implemented
1554
"""
1555
#Check to see if .first() and .next() are overridden in the subclass
1556
if ( self.first != self.__first_from_iterator and
1557
self.next != self.__next_from_iterator ):
1558
return self.__iterator_from_next()
1559
#Check to see if .last() and .previous() are overridden in the subclass
1560
elif ( self.last != self.__last_from_iterator and
1561
self.previous != self.__previous_from_iterator):
1562
return self.__iterator_from_previous()
1563
#Check to see if .unrank() is overridden in the subclass
1564
elif self.unrank != self.__unrank_from_iterator:
1565
return self.__iterator_from_unrank()
1566
#Finally, check to see if .list() is overridden in the subclass
1567
elif self.list != self.__list_from_iterator:
1568
return self.__iterator_from_list()
1569
else:
1570
raise NotImplementedError, "iterator called but not implemented"
1571
1572
def __unrank_from_iterator(self, r):
1573
"""
1574
Default implementation of unrank which goes through the iterator.
1575
1576
EXAMPLES::
1577
1578
sage: C = CombinatorialClass()
1579
sage: C.list = lambda: [1,2,3]
1580
sage: C.unrank(1) # indirect doctest
1581
2
1582
"""
1583
counter = 0
1584
for u in self:
1585
if counter == r:
1586
return u
1587
counter += 1
1588
raise ValueError, "the value must be between %s and %s inclusive"%(0,counter-1)
1589
1590
#Set the default implementation of unrank
1591
unrank = __unrank_from_iterator
1592
1593
1594
def __random_element_from_unrank(self):
1595
"""
1596
Default implementation of random which uses unrank.
1597
1598
EXAMPLES::
1599
1600
sage: C = CombinatorialClass()
1601
sage: C.list = lambda: [1,2,3]
1602
sage: C.random_element() # indirect doctest
1603
1
1604
"""
1605
c = self.cardinality()
1606
r = randint(0, c-1)
1607
return self.unrank(r)
1608
1609
1610
#Set the default implementation of random
1611
random_element = __random_element_from_unrank
1612
1613
def random(self):
1614
"""
1615
Deprecated. Use self.random_element() instead.
1616
1617
EXAMPLES::
1618
1619
sage: C = CombinatorialClass()
1620
sage: C.random()
1621
Traceback (most recent call last):
1622
...
1623
NotImplementedError: Deprecated: use random_element() instead
1624
"""
1625
raise NotImplementedError, "Deprecated: use random_element() instead"
1626
1627
def __rank_from_iterator(self, obj):
1628
"""
1629
Default implementation of rank which uses iterator.
1630
1631
EXAMPLES::
1632
1633
sage: C = CombinatorialClass()
1634
sage: C.list = lambda: [1,2,3]
1635
sage: C.rank(3) # indirect doctest
1636
2
1637
"""
1638
r = 0
1639
for i in self:
1640
if i == obj:
1641
return r
1642
r += 1
1643
raise ValueError
1644
1645
rank = __rank_from_iterator
1646
1647
def __first_from_iterator(self):
1648
"""
1649
Default implementation for first which uses iterator.
1650
1651
EXAMPLES::
1652
1653
sage: C = CombinatorialClass()
1654
sage: C.list = lambda: [1,2,3]
1655
sage: C.first() # indirect doctest
1656
1
1657
"""
1658
for i in self:
1659
return i
1660
1661
first = __first_from_iterator
1662
1663
def __last_from_iterator(self):
1664
"""
1665
Default implementation for first which uses iterator.
1666
1667
EXAMPLES::
1668
1669
sage: C = CombinatorialClass()
1670
sage: C.list = lambda: [1,2,3]
1671
sage: C.last() # indirect doctest
1672
3
1673
"""
1674
for i in self:
1675
pass
1676
return i
1677
1678
last = __last_from_iterator
1679
1680
def __next_from_iterator(self, obj):
1681
"""
1682
Default implementation for next which uses iterator.
1683
1684
EXAMPLES::
1685
1686
sage: C = CombinatorialClass()
1687
sage: C.list = lambda: [1,2,3]
1688
sage: C.next(2) # indirect doctest
1689
3
1690
"""
1691
found = False
1692
for i in self:
1693
if found:
1694
return i
1695
if i == obj:
1696
found = True
1697
return None
1698
1699
next = __next_from_iterator
1700
1701
def __previous_from_iterator(self, obj):
1702
"""
1703
Default implementation for next which uses iterator.
1704
1705
EXAMPLES::
1706
1707
sage: C = CombinatorialClass()
1708
sage: C.list = lambda: [1,2,3]
1709
sage: C.previous(2) # indirect doctest
1710
1
1711
"""
1712
prev = None
1713
for i in self:
1714
if i == obj:
1715
break
1716
prev = i
1717
return prev
1718
1719
previous = __previous_from_iterator
1720
1721
def filter(self, f, name=None):
1722
"""
1723
Returns the combinatorial subclass of f which consists of the
1724
elements x of self such that f(x) is True.
1725
1726
EXAMPLES::
1727
1728
sage: from sage.combinat.combinat import Permutations_CC
1729
sage: P = Permutations_CC(3).filter(lambda x: x.avoids([1,2]))
1730
sage: P.list()
1731
[[3, 2, 1]]
1732
"""
1733
return FilteredCombinatorialClass(self, f, name=name)
1734
1735
def union(self, right_cc, name=None):
1736
"""
1737
Returns the combinatorial class representing the union of self and
1738
right_cc.
1739
1740
EXAMPLES::
1741
1742
sage: from sage.combinat.combinat import Permutations_CC
1743
sage: P = Permutations_CC(2).union(Permutations_CC(1))
1744
sage: P.list()
1745
[[1, 2], [2, 1], [1]]
1746
"""
1747
if not isinstance(right_cc, CombinatorialClass):
1748
raise TypeError, "right_cc must be a CombinatorialClass"
1749
return UnionCombinatorialClass(self, right_cc, name=name)
1750
1751
def map(self, f, name=None):
1752
r"""
1753
Returns the image `\{f(x) | x \in \text{self}\}` of this combinatorial
1754
class by `f`, as a combinatorial class.
1755
1756
`f` is supposed to be injective.
1757
1758
EXAMPLES::
1759
1760
sage: R = Permutations(3).map(attrcall('reduced_word')); R
1761
Image of Standard permutations of 3 by *.reduced_word()
1762
sage: R.cardinality()
1763
6
1764
sage: R.list()
1765
[[], [2], [1], [1, 2], [2, 1], [2, 1, 2]]
1766
sage: [ r for r in R]
1767
[[], [2], [1], [1, 2], [2, 1], [2, 1, 2]]
1768
1769
If the function is not injective, then there may be repeated elements:
1770
sage: P = Partitions(4)
1771
sage: P.list()
1772
[[4], [3, 1], [2, 2], [2, 1, 1], [1, 1, 1, 1]]
1773
sage: P.map(len).list()
1774
[1, 2, 2, 3, 4]
1775
1776
TESTS::
1777
1778
sage: R = Permutations(3).map(attrcall('reduced_word'))
1779
sage: R == loads(dumps(R))
1780
True
1781
"""
1782
return MapCombinatorialClass(self, f, name)
1783
1784
class FilteredCombinatorialClass(CombinatorialClass):
1785
def __init__(self, combinatorial_class, f, name=None):
1786
"""
1787
A filtered combinatorial class F is a subset of another
1788
combinatorial class C specified by a function f that takes in an
1789
element c of C and returns True if and only if c is in F.
1790
1791
TESTS::
1792
1793
sage: from sage.combinat.combinat import Permutations_CC
1794
sage: Permutations_CC(3).filter(lambda x: x.avoids([1,2]))
1795
Filtered subclass of Standard permutations of 3
1796
"""
1797
self.f = f
1798
self.combinatorial_class = combinatorial_class
1799
self._name = name
1800
1801
def __repr__(self):
1802
"""
1803
EXAMPLES::
1804
1805
sage: from sage.combinat.combinat import Permutations_CC
1806
sage: P = Permutations_CC(3).filter(lambda x: x.avoids([1,2]))
1807
sage: P.__repr__()
1808
'Filtered subclass of Standard permutations of 3'
1809
sage: P._name = 'Permutations avoiding [1, 2]'
1810
sage: P.__repr__()
1811
'Permutations avoiding [1, 2]'
1812
"""
1813
if self._name:
1814
return self._name
1815
else:
1816
return "Filtered subclass of " + repr(self.combinatorial_class)
1817
1818
def __contains__(self, x):
1819
"""
1820
EXAMPLES::
1821
1822
sage: from sage.combinat.combinat import Permutations_CC
1823
sage: P = Permutations_CC(3).filter(lambda x: x.avoids([1,2]))
1824
sage: 'cat' in P
1825
False
1826
sage: [4,3,2,1] in P
1827
False
1828
sage: Permutation([1,2,3]) in P
1829
False
1830
sage: Permutation([3,2,1]) in P
1831
True
1832
"""
1833
return x in self.combinatorial_class and self.f(x)
1834
1835
def cardinality(self):
1836
"""
1837
EXAMPLES::
1838
1839
sage: from sage.combinat.combinat import Permutations_CC
1840
sage: P = Permutations_CC(3).filter(lambda x: x.avoids([1,2]))
1841
sage: P.cardinality()
1842
1
1843
"""
1844
c = 0
1845
for _ in self:
1846
c += 1
1847
return c
1848
1849
def __iter__(self):
1850
"""
1851
EXAMPLES::
1852
1853
sage: from sage.combinat.combinat import Permutations_CC
1854
sage: P = Permutations_CC(3).filter(lambda x: x.avoids([1,2]))
1855
sage: list(P)
1856
[[3, 2, 1]]
1857
"""
1858
for x in self.combinatorial_class:
1859
if self.f(x):
1860
yield x
1861
1862
class UnionCombinatorialClass(CombinatorialClass):
1863
def __init__(self, left_cc, right_cc, name=None):
1864
"""
1865
A UnionCombinatorialClass is a union of two other combinatorial
1866
classes.
1867
1868
TESTS::
1869
1870
sage: from sage.combinat.combinat import Permutations_CC
1871
sage: P = Permutations_CC(3).union(Permutations_CC(2))
1872
sage: P == loads(dumps(P))
1873
True
1874
"""
1875
self.left_cc = left_cc
1876
self.right_cc = right_cc
1877
self._name = name
1878
1879
def __repr__(self):
1880
"""
1881
TESTS::
1882
1883
sage: from sage.combinat.combinat import Permutations_CC
1884
sage: print repr(Permutations_CC(3).union(Permutations_CC(2)))
1885
Union combinatorial class of
1886
Standard permutations of 3
1887
and
1888
Standard permutations of 2
1889
"""
1890
if self._name:
1891
return self._name
1892
else:
1893
return "Union combinatorial class of \n %s\nand\n %s"%(self.left_cc, self.right_cc)
1894
1895
def __contains__(self, x):
1896
"""
1897
EXAMPLES::
1898
1899
sage: from sage.combinat.combinat import Permutations_CC
1900
sage: P = Permutations_CC(3).union(Permutations_CC(2))
1901
sage: [1,2] in P
1902
True
1903
sage: [3,2,1] in P
1904
True
1905
sage: [1,2,3,4] in P
1906
False
1907
"""
1908
return x in self.left_cc or x in self.right_cc
1909
1910
def cardinality(self):
1911
"""
1912
EXAMPLES::
1913
1914
sage: from sage.combinat.combinat import Permutations_CC
1915
sage: P = Permutations_CC(3).union(Permutations_CC(2))
1916
sage: P.cardinality()
1917
8
1918
"""
1919
return self.left_cc.cardinality() + self.right_cc.cardinality()
1920
1921
def list(self):
1922
"""
1923
EXAMPLES::
1924
1925
sage: from sage.combinat.combinat import Permutations_CC
1926
sage: P = Permutations_CC(3).union(Permutations_CC(2))
1927
sage: P.list()
1928
[[1, 2, 3],
1929
[1, 3, 2],
1930
[2, 1, 3],
1931
[2, 3, 1],
1932
[3, 1, 2],
1933
[3, 2, 1],
1934
[1, 2],
1935
[2, 1]]
1936
"""
1937
return self.left_cc.list() + self.right_cc.list()
1938
1939
1940
def __iter__(self):
1941
"""
1942
EXAMPLES::
1943
1944
sage: from sage.combinat.combinat import Permutations_CC
1945
sage: P = Permutations_CC(3).union(Permutations_CC(2))
1946
sage: list(P)
1947
[[1, 2, 3],
1948
[1, 3, 2],
1949
[2, 1, 3],
1950
[2, 3, 1],
1951
[3, 1, 2],
1952
[3, 2, 1],
1953
[1, 2],
1954
[2, 1]]
1955
"""
1956
for x in self.left_cc:
1957
yield x
1958
for x in self.right_cc:
1959
yield x
1960
1961
def first(self):
1962
"""
1963
EXAMPLES::
1964
1965
sage: from sage.combinat.combinat import Permutations_CC
1966
sage: P = Permutations_CC(3).union(Permutations_CC(2))
1967
sage: P.first()
1968
[1, 2, 3]
1969
"""
1970
return self.left_cc.first()
1971
1972
def last(self):
1973
"""
1974
EXAMPLES::
1975
1976
sage: from sage.combinat.combinat import Permutations_CC
1977
sage: P = Permutations_CC(3).union(Permutations_CC(2))
1978
sage: P.last()
1979
[2, 1]
1980
"""
1981
return self.right_cc.last()
1982
1983
def rank(self, x):
1984
"""
1985
EXAMPLES::
1986
1987
sage: from sage.combinat.combinat import Permutations_CC
1988
sage: P = Permutations_CC(3).union(Permutations_CC(2))
1989
sage: P.rank(Permutation([2,1]))
1990
7
1991
sage: P.rank(Permutation([1,2,3]))
1992
0
1993
"""
1994
try:
1995
return self.left_cc.rank(x)
1996
except (TypeError, ValueError):
1997
return self.left_cc.cardinality() + self.right_cc.rank(x)
1998
1999
def unrank(self, x):
2000
"""
2001
EXAMPLES::
2002
2003
sage: from sage.combinat.combinat import Permutations_CC
2004
sage: P = Permutations_CC(3).union(Permutations_CC(2))
2005
sage: P.unrank(7)
2006
[2, 1]
2007
sage: P.unrank(0)
2008
[1, 2, 3]
2009
"""
2010
try:
2011
return self.left_cc.unrank(x)
2012
except (TypeError, ValueError):
2013
return self.right_cc.unrank(x - self.left_cc.cardinality())
2014
2015
class Permutations_CC(CombinatorialClass):
2016
"""
2017
A testing class for :class:`CombinatorialClass` since :class:`Permutations`
2018
no longer inherits from :class:`CombinatorialClass` in :trac:`14772`.
2019
"""
2020
def __init__(self, n):
2021
"""
2022
EXAMPLES::
2023
2024
sage: from sage.combinat.combinat import Permutations_CC
2025
sage: P = Permutations_CC(4)
2026
sage: loads(dumps(P)) == P
2027
True
2028
"""
2029
from sage.combinat.permutation import StandardPermutations_n
2030
self._permutations = StandardPermutations_n(n)
2031
2032
def __repr__(self):
2033
"""
2034
EXAMPLES::
2035
2036
sage: from sage.combinat.combinat import Permutations_CC
2037
sage: Permutations_CC(3)
2038
Standard permutations of 3
2039
"""
2040
return repr(self._permutations)
2041
2042
def __contains__(self, x):
2043
"""
2044
EXAMPLES::
2045
2046
sage: from sage.combinat.combinat import Permutations_CC
2047
sage: P = Permutations_CC(3)
2048
sage: [1, 3, 2] in P
2049
True
2050
"""
2051
return x in self._permutations
2052
2053
def __iter__(self):
2054
"""
2055
EXAMPLES::
2056
2057
sage: from sage.combinat.combinat import Permutations_CC
2058
sage: P = Permutations_CC(3)
2059
sage: P.list()
2060
[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
2061
"""
2062
return self._permutations.__iter__()
2063
2064
##############################################################################
2065
class MapCombinatorialClass(CombinatorialClass):
2066
r"""
2067
A MapCombinatorialClass models the image of a combinatorial
2068
class through a function which is assumed to be injective
2069
2070
See CombinatorialClass.map for examples
2071
"""
2072
def __init__(self, cc, f, name=None):
2073
"""
2074
TESTS::
2075
2076
sage: Partitions(3).map(attrcall('conjugate'))
2077
Image of Partitions of the integer 3 by *.conjugate()
2078
"""
2079
self.cc = cc
2080
self.f = f
2081
self._name = name
2082
2083
def __repr__(self):
2084
"""
2085
TESTS::
2086
2087
sage: Partitions(3).map(attrcall('conjugate'))
2088
Image of Partitions of the integer 3 by *.conjugate()
2089
2090
"""
2091
if self._name:
2092
return self._name
2093
else:
2094
return "Image of %s by %s"%(self.cc, self.f)
2095
2096
def cardinality(self):
2097
"""
2098
Returns the cardinality of this combinatorial class
2099
2100
EXAMPLES::
2101
2102
sage: R = Permutations(10).map(attrcall('reduced_word'))
2103
sage: R.cardinality()
2104
3628800
2105
2106
"""
2107
return self.cc.cardinality()
2108
2109
def __iter__(self):
2110
"""
2111
Returns an iterator over the elements of this combinatorial class
2112
2113
EXAMPLES::
2114
2115
sage: R = Permutations(10).map(attrcall('reduced_word'))
2116
sage: R.cardinality()
2117
3628800
2118
"""
2119
for x in self.cc:
2120
yield self.f(x)
2121
2122
def an_element(self):
2123
"""
2124
Returns an element of this combinatorial class
2125
2126
EXAMPLES::
2127
2128
sage: R = SymmetricGroup(10).map(attrcall('reduced_word'))
2129
sage: R.an_element()
2130
[9, 8, 7, 6, 5, 4, 3, 2, 1]
2131
"""
2132
return self.f(self.cc.an_element())
2133
2134
##############################################################################
2135
from sage.rings.all import infinity
2136
class InfiniteAbstractCombinatorialClass(CombinatorialClass):
2137
r"""
2138
This is an internal class that should not be used directly. A class which
2139
inherits from InfiniteAbstractCombinatorialClass inherits the standard
2140
methods list and count.
2141
2142
If self._infinite_cclass_slice exists then self.__iter__ returns an
2143
iterator for self, otherwise raise NotImplementedError. The method
2144
self._infinite_cclass_slice is supposed to accept any integer as an
2145
argument and return something which is iterable.
2146
"""
2147
def cardinality(self):
2148
"""
2149
Counts the elements of the combinatorial class.
2150
2151
EXAMPLES:
2152
sage: R = InfiniteAbstractCombinatorialClass()
2153
sage: R.cardinality()
2154
+Infinity
2155
"""
2156
return infinity
2157
2158
def list(self):
2159
"""
2160
Returns an error since self is an infinite combinatorial class.
2161
2162
EXAMPLES:
2163
sage: R = InfiniteAbstractCombinatorialClass()
2164
sage: R.list()
2165
Traceback (most recent call last):
2166
...
2167
NotImplementedError: infinite list
2168
"""
2169
raise NotImplementedError, "infinite list"
2170
2171
def __iter__(self):
2172
"""
2173
Returns an iterator for the infinite combinatorial class self if
2174
possible or raise a NotImplementedError.
2175
2176
EXAMPLES:
2177
sage: R = InfiniteAbstractCombinatorialClass()
2178
sage: iter(R).next()
2179
Traceback (most recent call last):
2180
...
2181
NotImplementedError
2182
2183
sage: c = iter(Compositions()) # indirect doctest
2184
sage: c.next(), c.next(), c.next(), c.next(), c.next(), c.next()
2185
([], [1], [1, 1], [2], [1, 1, 1], [1, 2])
2186
sage: c.next(), c.next(), c.next(), c.next(), c.next(), c.next()
2187
([2, 1], [3], [1, 1, 1, 1], [1, 1, 2], [1, 2, 1], [1, 3])
2188
"""
2189
try:
2190
finite = self._infinite_cclass_slice
2191
except AttributeError:
2192
raise NotImplementedError
2193
i = 0
2194
while True:
2195
for c in finite(i):
2196
yield c
2197
i+=1
2198
2199
#####################################################
2200
#### combinatorial sets/lists
2201
2202
def combinations(mset,k):
2203
r"""
2204
A combination of a multiset (a list of objects which may contain
2205
the same object several times) mset is an unordered selection
2206
without repetitions and is represented by a sorted sublist of ``mset``.
2207
Returns the set of all combinations of the multiset ``mset`` with ``k``
2208
elements.
2209
2210
INPUT:
2211
2212
- ``mset`` -- (list) the multiset presented as a list of objects.
2213
2214
- ``k`` -- (integer) the size of each set.
2215
2216
.. NOTE::
2217
2218
This function is deprecated in favor of
2219
:func:`sage.combinat.combination.Combinations`. Use
2220
``Combinations(mset, k).list()`` directly to get the list of
2221
combinations of ``mset``.
2222
2223
EXAMPLES::
2224
2225
sage: combinations([1,2,3], 2)
2226
doctest:...: DeprecationWarning: Use Combinations(mset,k).list()
2227
instead. See http://trac.sagemath.org/13821 for details.
2228
[[1, 2], [1, 3], [2, 3]]
2229
sage: mset = [1,1,2,3,4,4,5]
2230
sage: combinations(mset,2)
2231
[[1, 1],
2232
[1, 2],
2233
[1, 3],
2234
[1, 4],
2235
[1, 5],
2236
[2, 3],
2237
[2, 4],
2238
[2, 5],
2239
[3, 4],
2240
[3, 5],
2241
[4, 4],
2242
[4, 5]]
2243
sage: mset = ["d","a","v","i","d"]
2244
sage: combinations(mset,3)
2245
[['d', 'd', 'a'],
2246
['d', 'd', 'v'],
2247
['d', 'd', 'i'],
2248
['d', 'a', 'v'],
2249
['d', 'a', 'i'],
2250
['d', 'v', 'i'],
2251
['a', 'v', 'i']]
2252
2253
It is possible to take combinations of Sage objects::
2254
2255
sage: combinations([vector([1,1]), vector([2,2]), vector([3,3])], 2)
2256
[[(1, 1), (2, 2)], [(1, 1), (3, 3)], [(2, 2), (3, 3)]]
2257
"""
2258
from sage.combinat.combination import Combinations
2259
deprecation(13821, 'Use Combinations(mset,k).list() instead.')
2260
return Combinations(mset, k).list()
2261
2262
def combinations_iterator(mset, k=None):
2263
"""
2264
An iterator for combinations of the elements of a multiset ``mset``.
2265
2266
INPUT:
2267
2268
- ``mset`` -- (list) the multiset presented as a list of objects.
2269
2270
- ``k`` -- (integer, default: None) the size of each set.
2271
2272
.. NOTE::
2273
2274
This function is deprecated in favor of
2275
:func:`sage.combinat.combination.Combinations`. Use
2276
``Combinations(mset, k)`` instead.
2277
2278
EXAMPLES::
2279
2280
sage: X = combinations_iterator([1,2,3,4,5],3)
2281
doctest:...: DeprecationWarning: Use Combinations(mset,k) instead.
2282
See http://trac.sagemath.org/13821 for details.
2283
sage: [x for x in X]
2284
[[1, 2, 3],
2285
[1, 2, 4],
2286
[1, 2, 5],
2287
[1, 3, 4],
2288
[1, 3, 5],
2289
[1, 4, 5],
2290
[2, 3, 4],
2291
[2, 3, 5],
2292
[2, 4, 5],
2293
[3, 4, 5]]
2294
"""
2295
# It is not possible to use deprecated_function_alias since it leads to
2296
# a circular import of combinat from combination and
2297
# combination.Combinations from combinat.
2298
from sage.combinat.combination import Combinations
2299
deprecation(13821, 'Use Combinations(mset,k) instead.')
2300
return Combinations(mset, k)
2301
2302
def number_of_combinations(mset,k):
2303
"""
2304
Returns the size of combinations(mset,k). IMPLEMENTATION: Wraps
2305
GAP's NrCombinations.
2306
2307
EXAMPLES::
2308
2309
sage: mset = [1,1,2,3,4,4,5]
2310
sage: number_of_combinations(mset,2)
2311
doctest:1: DeprecationWarning: Use Combinations(mset,k).cardinality() instead.
2312
See http://trac.sagemath.org/14138 for details.
2313
12
2314
"""
2315
from sage.combinat.combination import Combinations
2316
deprecation(14138, 'Use Combinations(mset,k).cardinality() instead.')
2317
return Combinations(mset,k).cardinality()
2318
2319
def arrangements(mset,k):
2320
r"""
2321
An arrangement of ``mset`` is an ordered selection without repetitions
2322
and is represented by a list that contains only elements from mset,
2323
but maybe in a different order.
2324
2325
``arrangements`` returns the set of arrangements of the
2326
multiset ``mset`` that contain ``k`` elements.
2327
2328
INPUT:
2329
2330
- ``mset`` -- (list) the multiset presented as a list of objects.
2331
2332
- ``k`` -- (integer) the size of each set.
2333
2334
.. NOTE::
2335
2336
This function is deprecated in favor of
2337
:func:`sage.combinat.permutation.Arrangements`. Use
2338
``Arrangements(mset, k).list()`` directly to get the list of
2339
arrangements of ``mset``.
2340
2341
EXAMPLES::
2342
2343
sage: arrangements([1,2,3], 2)
2344
doctest:...: DeprecationWarning: Use Arrangements(mset,k).list()
2345
instead. See http://trac.sagemath.org/13821 for details.
2346
[[1, 2], [1, 3], [2, 1], [2, 3], [3, 1], [3, 2]]
2347
sage: mset = [1,1,2,3,4,4,5]
2348
sage: arrangements(mset,2)
2349
[[1, 1],
2350
[1, 2],
2351
[1, 3],
2352
[1, 4],
2353
[1, 5],
2354
[2, 1],
2355
[2, 3],
2356
[2, 4],
2357
[2, 5],
2358
[3, 1],
2359
[3, 2],
2360
[3, 4],
2361
[3, 5],
2362
[4, 1],
2363
[4, 2],
2364
[4, 3],
2365
[4, 4],
2366
[4, 5],
2367
[5, 1],
2368
[5, 2],
2369
[5, 3],
2370
[5, 4]]
2371
sage: arrangements( ["c","a","t"], 2 )
2372
[['c', 'a'], ['c', 't'], ['a', 'c'],
2373
['a', 't'], ['t', 'c'], ['t', 'a']]
2374
sage: arrangements( ["c","a","t"], 3 )
2375
[['c', 'a', 't'], ['c', 't', 'a'], ['a', 'c', 't'],
2376
['a', 't', 'c'], ['t', 'c', 'a'], ['t', 'a', 'c']]
2377
"""
2378
from sage.combinat.permutation import Arrangements
2379
deprecation(13821, 'Use Arrangements(mset,k).list() instead.')
2380
return Arrangements(mset, k).list()
2381
2382
def number_of_arrangements(mset,k):
2383
"""
2384
Returns the size of arrangements(mset,k).
2385
2386
EXAMPLES::
2387
2388
sage: mset = [1,1,2,3,4,4,5]
2389
sage: number_of_arrangements(mset,2)
2390
doctest:1: DeprecationWarning: Use Arrangements(mset,k).cardinality() instead.
2391
See http://trac.sagemath.org/14138 for details.
2392
22
2393
"""
2394
from sage.combinat.permutation import Arrangements
2395
deprecation(14138, 'Use Arrangements(mset,k).cardinality() instead.')
2396
return Arrangements(mset, k).cardinality()
2397
2398
def derangements(mset):
2399
"""
2400
This is deprecated in :trac:`9005`. Use instead :class:`Derangements`.
2401
2402
EXAMPLES::
2403
2404
sage: mset = [1,2,3,4]
2405
sage: D = derangements(mset); D
2406
doctest:1: DeprecationWarning: derangements() is deprecated. Use Derangements instead.
2407
See http://trac.sagemath.org/9005 for details.
2408
Derangements of the set [1, 2, 3, 4]
2409
"""
2410
from sage.misc.superseded import deprecation
2411
deprecation(9005,'derangements() is deprecated. Use Derangements instead.')
2412
from sage.combinat.derangements import Derangements
2413
return Derangements(mset)
2414
2415
def number_of_derangements(mset):
2416
"""
2417
This is deprecated in :trac:`9005`. Use :meth:`Derangements.cardinality()`
2418
instead.
2419
2420
EXAMPLES::
2421
2422
sage: mset = [1,2,3,4]
2423
sage: number_of_derangements(mset)
2424
doctest:1: DeprecationWarning: number_of_derangements() is deprecated. Use Derangements.cardinality() instead.
2425
See http://trac.sagemath.org/9005 for details.
2426
9
2427
"""
2428
from sage.misc.superseded import deprecation
2429
deprecation(9005,'number_of_derangements() is deprecated. Use Derangements.cardinality() instead.')
2430
from sage.combinat.derangements import Derangements
2431
return Derangements(mset).cardinality()
2432
2433
def tuples(S,k):
2434
"""
2435
An ordered tuple of length k of set is an ordered selection with
2436
repetition and is represented by a list of length k containing
2437
elements of set. tuples returns the set of all ordered tuples of
2438
length k of the set.
2439
2440
EXAMPLES::
2441
2442
sage: S = [1,2]
2443
sage: tuples(S,3)
2444
[[1, 1, 1], [2, 1, 1], [1, 2, 1], [2, 2, 1], [1, 1, 2], [2, 1, 2], [1, 2, 2], [2, 2, 2]]
2445
sage: mset = ["s","t","e","i","n"]
2446
sage: tuples(mset,2)
2447
[['s', 's'], ['t', 's'], ['e', 's'], ['i', 's'], ['n', 's'], ['s', 't'], ['t', 't'],
2448
['e', 't'], ['i', 't'], ['n', 't'], ['s', 'e'], ['t', 'e'], ['e', 'e'], ['i', 'e'],
2449
['n', 'e'], ['s', 'i'], ['t', 'i'], ['e', 'i'], ['i', 'i'], ['n', 'i'], ['s', 'n'],
2450
['t', 'n'], ['e', 'n'], ['i', 'n'], ['n', 'n']]
2451
2452
The Set(...) comparisons are necessary because finite fields are
2453
not enumerated in a standard order.
2454
2455
::
2456
2457
sage: K.<a> = GF(4, 'a')
2458
sage: mset = [x for x in K if x!=0]
2459
sage: tuples(mset,2)
2460
[[a, a], [a + 1, a], [1, a], [a, a + 1], [a + 1, a + 1], [1, a + 1], [a, 1], [a + 1, 1], [1, 1]]
2461
2462
AUTHORS:
2463
2464
- Jon Hanke (2006-08)
2465
"""
2466
import copy
2467
if k<=0:
2468
return [[]]
2469
if k==1:
2470
return [[x] for x in S]
2471
ans = []
2472
for s in S:
2473
for x in tuples(S,k-1):
2474
y = copy.copy(x)
2475
y.append(s)
2476
ans.append(y)
2477
return ans
2478
2479
def number_of_tuples(S,k):
2480
"""
2481
Returns the size of tuples(S,k). Wraps GAP's NrTuples.
2482
2483
EXAMPLES::
2484
2485
sage: S = [1,2,3,4,5]
2486
sage: number_of_tuples(S,2)
2487
25
2488
sage: S = [1,1,2,3,4,5]
2489
sage: number_of_tuples(S,2)
2490
25
2491
"""
2492
ans=gap.eval("NrTuples(%s,%s)"%(S,ZZ(k)))
2493
return ZZ(ans)
2494
2495
def unordered_tuples(S,k):
2496
"""
2497
An unordered tuple of length k of set is a unordered selection with
2498
repetitions of set and is represented by a sorted list of length k
2499
containing elements from set.
2500
2501
unordered_tuples returns the set of all unordered tuples of length
2502
k of the set. Wraps GAP's UnorderedTuples.
2503
2504
.. warning::
2505
2506
Wraps GAP - hence mset must be a list of objects that have
2507
string representations that can be interpreted by the GAP
2508
interpreter. If mset consists of at all complicated Sage
2509
objects, this function does *not* do what you expect. A proper
2510
function should be written! (TODO!)
2511
2512
EXAMPLES::
2513
2514
sage: S = [1,2]
2515
sage: unordered_tuples(S,3)
2516
[[1, 1, 1], [1, 1, 2], [1, 2, 2], [2, 2, 2]]
2517
sage: unordered_tuples(["a","b","c"],2)
2518
['aa', 'ab', 'ac', 'bb', 'bc', 'cc']
2519
"""
2520
ans=gap.eval("UnorderedTuples(%s,%s)"%(S,ZZ(k)))
2521
return eval(ans)
2522
2523
def number_of_unordered_tuples(S,k):
2524
"""
2525
Returns the size of unordered_tuples(S,k). Wraps GAP's
2526
NrUnorderedTuples.
2527
2528
EXAMPLES::
2529
2530
sage: S = [1,2,3,4,5]
2531
sage: number_of_unordered_tuples(S,2)
2532
15
2533
"""
2534
ans=gap.eval("NrUnorderedTuples(%s,%s)"%(S,ZZ(k)))
2535
return ZZ(ans)
2536
2537
def permutations(mset):
2538
"""
2539
This is deprecated in :trac:`14772`. Use :class:`Permutations` instead.
2540
To get the same output as `permutations(mset)`, use
2541
``Permutations(mset).list()``.
2542
2543
A permutation is represented by a list that contains exactly the
2544
same elements as mset, but possibly in different order. If mset is
2545
a proper set there are `|mset| !` such permutations.
2546
Otherwise if the first elements appears `k_1` times, the
2547
second element appears `k_2` times and so on, the number
2548
of permutations is `|mset|! / (k_1! k_2! \ldots)`, which
2549
is sometimes called a multinomial coefficient.
2550
2551
``permutations`` returns the list of all permutations of a multiset.
2552
2553
EXAMPLES::
2554
2555
sage: mset = [1,1,2,2,2]
2556
sage: permutations(mset)
2557
doctest:...: DeprecationWarning: Use the Permutations object instead.
2558
See http://trac.sagemath.org/14772 for details.
2559
[[1, 1, 2, 2, 2],
2560
[1, 2, 1, 2, 2],
2561
[1, 2, 2, 1, 2],
2562
[1, 2, 2, 2, 1],
2563
[2, 1, 1, 2, 2],
2564
[2, 1, 2, 1, 2],
2565
[2, 1, 2, 2, 1],
2566
[2, 2, 1, 1, 2],
2567
[2, 2, 1, 2, 1],
2568
[2, 2, 2, 1, 1]]
2569
sage: MS = MatrixSpace(GF(2),2,2)
2570
sage: A = MS([1,0,1,1])
2571
sage: rows = A.rows()
2572
sage: rows[0].set_immutable()
2573
sage: rows[1].set_immutable()
2574
sage: permutations(rows)
2575
[[(1, 0), (1, 1)], [(1, 1), (1, 0)]]
2576
"""
2577
deprecation(14772, 'Use the Permutations object instead.')
2578
from sage.combinat.permutation import Permutations
2579
ans = Permutations(mset)
2580
return ans.list()
2581
2582
def permutations_iterator(mset,n=None):
2583
"""
2584
Do not use this function. It is deprecated in :trac:`14138`.
2585
Use Permutations instead. For example, instead of
2586
2587
``for p in permutations_iterator(range(1, m+1), n)``
2588
2589
use
2590
2591
``for p in Permutations(m, n)``.
2592
2593
Note that :class:`Permutations`, unlike this function, treats repeated
2594
elements as identical.
2595
2596
If you insist on using this now:
2597
2598
Returns an iterator (http://docs.python.org/lib/typeiter.html)
2599
which can be used in place of permutations(mset) if all you need it
2600
for is a 'for' loop.
2601
2602
Posted by Raymond Hettinger, 2006/03/23, to the Python Cookbook:
2603
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/474124
2604
2605
Note- This function considers repeated elements as different
2606
entries, so for example::
2607
2608
sage: from sage.combinat.combinat import permutations, permutations_iterator
2609
sage: mset = [1,2,2]
2610
sage: permutations(mset)
2611
doctest:...: DeprecationWarning: Use the Permutations object instead.
2612
See http://trac.sagemath.org/14772 for details.
2613
[[1, 2, 2], [2, 1, 2], [2, 2, 1]]
2614
sage: for p in permutations_iterator(mset): print p
2615
doctest:...: DeprecationWarning: Use the Permutations object instead.
2616
See http://trac.sagemath.org/14138 for details.
2617
[1, 2, 2]
2618
[2, 1, 2]
2619
[2, 2, 1]
2620
[2, 1, 2]
2621
[2, 2, 1]
2622
2623
EXAMPLES::
2624
2625
sage: X = permutations_iterator(range(3),2)
2626
sage: [x for x in X]
2627
[[0, 1], [0, 2], [1, 0], [1, 2], [2, 0], [2, 1]]
2628
"""
2629
deprecation(14138, 'Use the Permutations object instead.')
2630
items = mset
2631
if n is None:
2632
n = len(items)
2633
from sage.combinat.permutation import Permutations
2634
for i in range(len(items)):
2635
v = items[i:i+1]
2636
if n == 1:
2637
yield v
2638
else:
2639
rest = items[:i] + items[i+1:]
2640
for p in Permutations(rest, n-1):
2641
yield v + list(p)
2642
2643
def number_of_permutations(mset):
2644
"""
2645
Do not use this function. It was deprecated in :trac:`14138`.
2646
Use :class:`Permutations` instead. For example, instead of
2647
2648
``number_of_permutations(mset)``
2649
2650
use
2651
2652
``Permutations(mset).cardinality()``.
2653
2654
If you insist on using this now:
2655
2656
Returns the size of permutations(mset).
2657
2658
AUTHORS:
2659
2660
- Robert L. Miller
2661
2662
EXAMPLES::
2663
2664
sage: mset = [1,1,2,2,2]
2665
sage: number_of_permutations(mset)
2666
doctest:...: DeprecationWarning: Use the Permutations object instead.
2667
See http://trac.sagemath.org/14138 for details.
2668
10
2669
"""
2670
deprecation(14138, 'Use the Permutations object instead.')
2671
from sage.combinat.permutation import Permutations
2672
return Permutations(mset).cardinality()
2673
2674
def cyclic_permutations(mset):
2675
"""
2676
This function is deprecated in :trac:`14772`. Use instead
2677
:class:`CyclicPermutations`.
2678
2679
Return a list of all cyclic permutations of ``mset``. Treats ``mset``
2680
as a list, not a set, i.e. entries with the same value are distinct.
2681
2682
Note that :class:`CyclicPermutations`, unlike this function, treats
2683
repeated elements as identical.
2684
2685
AUTHORS:
2686
2687
- Emily Kirkman
2688
2689
EXAMPLES::
2690
2691
sage: from sage.combinat.combinat import cyclic_permutations, cyclic_permutations_iterator
2692
sage: cyclic_permutations(range(4))
2693
doctest:...: DeprecationWarning: Use the CyclicPermutations object instead.
2694
See http://trac.sagemath.org/14772 for details.
2695
doctest:...: DeprecationWarning: Use the CyclicPermutations object instead.
2696
See http://trac.sagemath.org/14772 for details.
2697
[[0, 1, 2, 3], [0, 1, 3, 2], [0, 2, 1, 3], [0, 2, 3, 1], [0, 3, 1, 2], [0, 3, 2, 1]]
2698
sage: for cycle in cyclic_permutations(['a', 'b', 'c']):
2699
....: print cycle
2700
['a', 'b', 'c']
2701
['a', 'c', 'b']
2702
2703
Since :trac:`14138` some repetitions are handled as expected::
2704
2705
sage: cyclic_permutations([1,1,1])
2706
[[1, 1, 1]]
2707
"""
2708
deprecation(14772, 'Use the CyclicPermutations object instead.')
2709
return list(cyclic_permutations_iterator(mset))
2710
2711
def cyclic_permutations_iterator(mset):
2712
"""
2713
This function is deprecated in :trac:`14772`. Use instead
2714
:class:`CyclicPermutations`.
2715
2716
Iterates over all cyclic permutations of ``mset`` in cycle notation.
2717
Treats ``mset`` as a list, not a set, i.e. entries with the same value
2718
are distinct.
2719
2720
Note that :class:`CyclicPermutations`, unlike this function, treats
2721
repeated elements as identical.
2722
2723
AUTHORS:
2724
2725
- Emily Kirkman
2726
2727
EXAMPLES::
2728
2729
sage: from sage.combinat.combinat import cyclic_permutations, cyclic_permutations_iterator
2730
sage: cyclic_permutations(range(4))
2731
doctest:...: DeprecationWarning: Use the CyclicPermutations object instead.
2732
See http://trac.sagemath.org/14772 for details.
2733
[[0, 1, 2, 3], [0, 1, 3, 2], [0, 2, 1, 3], [0, 2, 3, 1], [0, 3, 1, 2], [0, 3, 2, 1]]
2734
sage: for cycle in cyclic_permutations(['a', 'b', 'c']):
2735
....: print cycle
2736
['a', 'b', 'c']
2737
['a', 'c', 'b']
2738
2739
Since :trac:`14138` some repetitions are handled as expected::
2740
2741
sage: cyclic_permutations([1,1,1])
2742
[[1, 1, 1]]
2743
"""
2744
deprecation(14772, 'Use the CyclicPermutations object instead.')
2745
if len(mset) > 2:
2746
from sage.combinat.permutation import Permutations
2747
for perm in Permutations(mset[1:]):
2748
yield [mset[0]] + list(perm)
2749
else:
2750
yield mset
2751
2752
def bell_polynomial(n, k):
2753
r"""
2754
This function returns the Bell Polynomial
2755
2756
.. math::
2757
2758
B_{n,k}(x_1, x_2, \ldots, x_{n-k+1}) = \sum_{\sum{j_i}=k, \sum{i j_i}
2759
=n} \frac{n!}{j_1!j_2!\ldots} \frac{x_1}{1!}^j_1 \frac{x_2}{2!}^j_2
2760
\ldots
2761
2762
INPUT:
2763
2764
- ``n`` - integer
2765
2766
- ``k`` - integer
2767
2768
OUTPUT:
2769
2770
- polynomial expression (SymbolicArithmetic)
2771
2772
EXAMPLES::
2773
2774
sage: bell_polynomial(6,2)
2775
10*x_3^2 + 15*x_2*x_4 + 6*x_1*x_5
2776
sage: bell_polynomial(6,3)
2777
15*x_2^3 + 60*x_1*x_2*x_3 + 15*x_1^2*x_4
2778
2779
REFERENCES:
2780
2781
- E.T. Bell, "Partition Polynomials"
2782
2783
AUTHORS:
2784
2785
- Blair Sutton (2009-01-26)
2786
"""
2787
from sage.combinat.partition import Partitions
2788
from sage.rings.arith import factorial
2789
vars = ZZ[tuple(['x_'+str(i) for i in range(1, n-k+2)])].gens()
2790
result = 0
2791
for p in Partitions(n, length=k):
2792
factorial_product = 1
2793
power_factorial_product = 1
2794
for part, count in p.to_exp_dict().iteritems():
2795
factorial_product *= factorial(count)
2796
power_factorial_product *= factorial(part)**count
2797
2798
coefficient = factorial(n) / (factorial_product * power_factorial_product)
2799
result += coefficient * prod([vars[i-1] for i in p])
2800
2801
return result
2802
2803
def fibonacci_sequence(start, stop=None, algorithm=None):
2804
r"""
2805
Returns an iterator over the Fibonacci sequence, for all fibonacci
2806
numbers `f_n` from ``n = start`` up to (but
2807
not including) ``n = stop``
2808
2809
INPUT:
2810
2811
2812
- ``start`` - starting value
2813
2814
- ``stop`` - stopping value
2815
2816
- ``algorithm`` - default (None) - passed on to
2817
fibonacci function (or not passed on if None, i.e., use the
2818
default).
2819
2820
2821
EXAMPLES::
2822
2823
sage: fibs = [i for i in fibonacci_sequence(10, 20)]
2824
sage: fibs
2825
[55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181]
2826
2827
::
2828
2829
sage: sum([i for i in fibonacci_sequence(100, 110)])
2830
69919376923075308730013
2831
2832
.. seealso::
2833
2834
:func:`fibonacci_xrange`
2835
2836
AUTHORS:
2837
2838
- Bobby Moretti
2839
"""
2840
if stop is None:
2841
stop = ZZ(start)
2842
start = ZZ(0)
2843
else:
2844
start = ZZ(start)
2845
stop = ZZ(stop)
2846
2847
if algorithm:
2848
for n in xrange(start, stop):
2849
yield fibonacci(n, algorithm=algorithm)
2850
else:
2851
for n in xrange(start, stop):
2852
yield fibonacci(n)
2853
2854
def fibonacci_xrange(start, stop=None, algorithm='pari'):
2855
r"""
2856
Returns an iterator over all of the Fibonacci numbers in the given
2857
range, including ``f_n = start`` up to, but not
2858
including, ``f_n = stop``.
2859
2860
EXAMPLES::
2861
2862
sage: fibs_in_some_range = [i for i in fibonacci_xrange(10^7, 10^8)]
2863
sage: len(fibs_in_some_range)
2864
4
2865
sage: fibs_in_some_range
2866
[14930352, 24157817, 39088169, 63245986]
2867
2868
::
2869
2870
sage: fibs = [i for i in fibonacci_xrange(10, 100)]
2871
sage: fibs
2872
[13, 21, 34, 55, 89]
2873
2874
::
2875
2876
sage: list(fibonacci_xrange(13, 34))
2877
[13, 21]
2878
2879
A solution to the second Project Euler problem::
2880
2881
sage: sum([i for i in fibonacci_xrange(10^6) if is_even(i)])
2882
1089154
2883
2884
.. seealso::
2885
2886
:func:`fibonacci_sequence`
2887
2888
AUTHORS:
2889
2890
- Bobby Moretti
2891
"""
2892
if stop is None:
2893
stop = ZZ(start)
2894
start = ZZ(0)
2895
else:
2896
start = ZZ(start)
2897
stop = ZZ(stop)
2898
2899
# iterate until we've gotten high enough
2900
fn = 0
2901
n = 0
2902
while fn < start:
2903
n += 1
2904
fn = fibonacci(n)
2905
2906
while True:
2907
fn = fibonacci(n)
2908
n += 1
2909
if fn < stop:
2910
yield fn
2911
else:
2912
return
2913
2914
def bernoulli_polynomial(x, n):
2915
r"""
2916
Return the nth Bernoulli polynomial evaluated at x.
2917
2918
The generating function for the Bernoulli polynomials is
2919
2920
.. math::
2921
2922
\frac{t e^{xt}}{e^t-1}= \sum_{n=0}^\infty B_n(x) \frac{t^n}{n!},
2923
2924
and they are given directly by
2925
2926
.. math::
2927
2928
B_n(x) = \sum_{i=0}^n \binom{n}{i}B_{n-i}x^i.
2929
2930
One has `B_n(x) = - n\zeta(1 - n,x)`, where
2931
`\zeta(s,x)` is the Hurwitz zeta function. Thus, in a
2932
certain sense, the Hurwitz zeta function generalizes the
2933
Bernoulli polynomials to non-integer values of n.
2934
2935
EXAMPLES::
2936
2937
sage: y = QQ['y'].0
2938
sage: bernoulli_polynomial(y, 5)
2939
y^5 - 5/2*y^4 + 5/3*y^3 - 1/6*y
2940
sage: bernoulli_polynomial(y, 5)(12)
2941
199870
2942
sage: bernoulli_polynomial(12, 5)
2943
199870
2944
sage: bernoulli_polynomial(y^2 + 1, 5)
2945
y^10 + 5/2*y^8 + 5/3*y^6 - 1/6*y^2
2946
sage: P.<t> = ZZ[]
2947
sage: p = bernoulli_polynomial(t, 6)
2948
sage: p.parent()
2949
Univariate Polynomial Ring in t over Rational Field
2950
2951
We verify an instance of the formula which is the origin of
2952
the Bernoulli polynomials (and numbers)::
2953
2954
sage: power_sum = sum(k^4 for k in range(10))
2955
sage: 5*power_sum == bernoulli_polynomial(10, 5) - bernoulli(5)
2956
True
2957
2958
2959
REFERENCES:
2960
2961
- http://en.wikipedia.org/wiki/Bernoulli_polynomials
2962
"""
2963
try:
2964
n = ZZ(n)
2965
if n < 0:
2966
raise TypeError
2967
except TypeError:
2968
raise ValueError, "The second argument must be a non-negative integer"
2969
2970
if n == 0:
2971
return ZZ(1)
2972
2973
if n == 1:
2974
return x - ZZ(1)/2
2975
2976
k = n.mod(2)
2977
coeffs = [0]*k + sum(([binomial(n, i)*bernoulli(n-i), 0]
2978
for i in range(k, n+1, 2)), [])
2979
coeffs[-3] = -n/2
2980
2981
if isinstance(x, Polynomial):
2982
try:
2983
return x.parent()(coeffs)(x)
2984
except TypeError:
2985
pass
2986
2987
x2 = x*x
2988
xi = x**k
2989
s = 0
2990
for i in range(k, n-1, 2):
2991
s += coeffs[i]*xi
2992
t = xi
2993
xi *= x2
2994
s += xi - t*x*n/2
2995
return s
2996
2997