forked from sympy/sympy
/
iterables.py
2017 lines (1636 loc) · 55.8 KB
/
iterables.py
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import print_function, division
from collections import defaultdict
from itertools import combinations, permutations, product, product as cartes
import random
from operator import gt
from sympy.core.decorators import deprecated
from sympy.core import Basic, C
# this is the logical location of these functions
from sympy.core.compatibility import (
as_int, combinations_with_replacement, default_sort_key, is_sequence,
iterable, ordered, xrange
)
def flatten(iterable, levels=None, cls=None):
"""
Recursively denest iterable containers.
>>> from sympy.utilities.iterables import flatten
>>> flatten([1, 2, 3])
[1, 2, 3]
>>> flatten([1, 2, [3]])
[1, 2, 3]
>>> flatten([1, [2, 3], [4, 5]])
[1, 2, 3, 4, 5]
>>> flatten([1.0, 2, (1, None)])
[1.0, 2, 1, None]
If you want to denest only a specified number of levels of
nested containers, then set ``levels`` flag to the desired
number of levels::
>>> ls = [[(-2, -1), (1, 2)], [(0, 0)]]
>>> flatten(ls, levels=1)
[(-2, -1), (1, 2), (0, 0)]
If cls argument is specified, it will only flatten instances of that
class, for example:
>>> from sympy.core import Basic
>>> class MyOp(Basic):
... pass
...
>>> flatten([MyOp(1, MyOp(2, 3))], cls=MyOp)
[1, 2, 3]
adapted from http://kogs-www.informatik.uni-hamburg.de/~meine/python_tricks
"""
if levels is not None:
if not levels:
return iterable
elif levels > 0:
levels -= 1
else:
raise ValueError(
"expected non-negative number of levels, got %s" % levels)
if cls is None:
reducible = lambda x: is_sequence(x, set)
else:
reducible = lambda x: isinstance(x, cls)
result = []
for el in iterable:
if reducible(el):
if hasattr(el, 'args'):
el = el.args
result.extend(flatten(el, levels=levels, cls=cls))
else:
result.append(el)
return result
def unflatten(iter, n=2):
"""Group ``iter`` into tuples of length ``n``. Raise an error if
the length of ``iter`` is not a multiple of ``n``.
"""
if n < 1 or len(iter) % n:
raise ValueError('iter length is not a multiple of %i' % n)
return list(zip(*(iter[i::n] for i in xrange(n))))
def reshape(seq, how):
"""Reshape the sequence according to the template in ``how``.
Examples
========
>>> from sympy.utilities import reshape
>>> seq = list(range(1, 9))
>>> reshape(seq, [4]) # lists of 4
[[1, 2, 3, 4], [5, 6, 7, 8]]
>>> reshape(seq, (4,)) # tuples of 4
[(1, 2, 3, 4), (5, 6, 7, 8)]
>>> reshape(seq, (2, 2)) # tuples of 4
[(1, 2, 3, 4), (5, 6, 7, 8)]
>>> reshape(seq, (2, [2])) # (i, i, [i, i])
[(1, 2, [3, 4]), (5, 6, [7, 8])]
>>> reshape(seq, ((2,), [2])) # etc....
[((1, 2), [3, 4]), ((5, 6), [7, 8])]
>>> reshape(seq, (1, [2], 1))
[(1, [2, 3], 4), (5, [6, 7], 8)]
>>> reshape(tuple(seq), ([[1], 1, (2,)],))
(([[1], 2, (3, 4)],), ([[5], 6, (7, 8)],))
>>> reshape(tuple(seq), ([1], 1, (2,)))
(([1], 2, (3, 4)), ([5], 6, (7, 8)))
>>> reshape(list(range(12)), [2, [3], set([2]), (1, (3,), 1)])
[[0, 1, [2, 3, 4], set([5, 6]), (7, (8, 9, 10), 11)]]
"""
m = sum(flatten(how))
n, rem = divmod(len(seq), m)
if m < 0 or rem:
raise ValueError('template must sum to positive number '
'that divides the length of the sequence')
i = 0
container = type(how)
rv = [None]*n
for k in range(len(rv)):
rv[k] = []
for hi in how:
if type(hi) is int:
rv[k].extend(seq[i: i + hi])
i += hi
else:
n = sum(flatten(hi))
hi_type = type(hi)
rv[k].append(hi_type(reshape(seq[i: i + n], hi)[0]))
i += n
rv[k] = container(rv[k])
return type(seq)(rv)
def group(seq, multiple=True):
"""
Splits a sequence into a list of lists of equal, adjacent elements.
Examples
========
>>> from sympy.utilities.iterables import group
>>> group([1, 1, 1, 2, 2, 3])
[[1, 1, 1], [2, 2], [3]]
>>> group([1, 1, 1, 2, 2, 3], multiple=False)
[(1, 3), (2, 2), (3, 1)]
>>> group([1, 1, 3, 2, 2, 1], multiple=False)
[(1, 2), (3, 1), (2, 2), (1, 1)]
See Also
========
multiset
"""
if not seq:
return []
current, groups = [seq[0]], []
for elem in seq[1:]:
if elem == current[-1]:
current.append(elem)
else:
groups.append(current)
current = [elem]
groups.append(current)
if multiple:
return groups
for i, current in enumerate(groups):
groups[i] = (current[0], len(current))
return groups
def multiset(seq):
"""Return the hashable sequence in multiset form with values being the
multiplicity of the item in the sequence.
Examples
========
>>> from sympy.utilities.iterables import multiset
>>> multiset('mississippi')
{'i': 4, 'm': 1, 'p': 2, 's': 4}
See Also
========
group
"""
rv = defaultdict(int)
for s in seq:
rv[s] += 1
return dict(rv)
def postorder_traversal(node, keys=None):
"""
Do a postorder traversal of a tree.
This generator recursively yields nodes that it has visited in a postorder
fashion. That is, it descends through the tree depth-first to yield all of
a node's children's postorder traversal before yielding the node itself.
Parameters
==========
node : sympy expression
The expression to traverse.
keys : (default None) sort key(s)
The key(s) used to sort args of Basic objects. When None, args of Basic
objects are processed in arbitrary order. If key is defined, it will
be passed along to ordered() as the only key(s) to use to sort the
arguments; if ``key`` is simply True then the default keys of
``ordered`` will be used (node count and default_sort_key).
Yields
======
subtree : sympy expression
All of the subtrees in the tree.
Examples
========
>>> from sympy.utilities.iterables import postorder_traversal
>>> from sympy.abc import w, x, y, z
The nodes are returned in the order that they are encountered unless key
is given; simply passing key=True will guarantee that the traversal is
unique.
>>> list(postorder_traversal(w + (x + y)*z)) # doctest: +SKIP
[z, y, x, x + y, z*(x + y), w, w + z*(x + y)]
>>> list(postorder_traversal(w + (x + y)*z, keys=True))
[w, z, x, y, x + y, z*(x + y), w + z*(x + y)]
"""
if isinstance(node, Basic):
args = node.args
if keys:
if keys != True:
args = ordered(args, keys, default=False)
else:
args = ordered(args)
for arg in args:
for subtree in postorder_traversal(arg, keys):
yield subtree
elif iterable(node):
for item in node:
for subtree in postorder_traversal(item, keys):
yield subtree
yield node
def interactive_traversal(expr):
"""Traverse a tree asking a user which branch to choose. """
from sympy.printing import pprint
RED, BRED = '\033[0;31m', '\033[1;31m'
GREEN, BGREEN = '\033[0;32m', '\033[1;32m'
YELLOW, BYELLOW = '\033[0;33m', '\033[1;33m'
BLUE, BBLUE = '\033[0;34m', '\033[1;34m'
MAGENTA, BMAGENTA = '\033[0;35m', '\033[1;35m'
CYAN, BCYAN = '\033[0;36m', '\033[1;36m'
END = '\033[0m'
def cprint(*args):
print("".join(map(str, args)) + END)
def _interactive_traversal(expr, stage):
if stage > 0:
print()
cprint("Current expression (stage ", BYELLOW, stage, END, "):")
print(BCYAN)
pprint(expr)
print(END)
if isinstance(expr, Basic):
if expr.is_Add:
args = expr.as_ordered_terms()
elif expr.is_Mul:
args = expr.as_ordered_factors()
else:
args = expr.args
elif hasattr(expr, "__iter__"):
args = list(expr)
else:
return expr
n_args = len(args)
if not n_args:
return expr
for i, arg in enumerate(args):
cprint(GREEN, "[", BGREEN, i, GREEN, "] ", BLUE, type(arg), END)
pprint(arg)
print
if n_args == 1:
choices = '0'
else:
choices = '0-%d' % (n_args - 1)
try:
choice = raw_input("Your choice [%s,f,l,r,d,?]: " % choices)
except EOFError:
result = expr
print()
else:
if choice == '?':
cprint(RED, "%s - select subexpression with the given index" %
choices)
cprint(RED, "f - select the first subexpression")
cprint(RED, "l - select the last subexpression")
cprint(RED, "r - select a random subexpression")
cprint(RED, "d - done\n")
result = _interactive_traversal(expr, stage)
elif choice in ['d', '']:
result = expr
elif choice == 'f':
result = _interactive_traversal(args[0], stage + 1)
elif choice == 'l':
result = _interactive_traversal(args[-1], stage + 1)
elif choice == 'r':
result = _interactive_traversal(random.choice(args), stage + 1)
else:
try:
choice = int(choice)
except ValueError:
cprint(BRED,
"Choice must be a number in %s range\n" % choices)
result = _interactive_traversal(expr, stage)
else:
if choice < 0 or choice >= n_args:
cprint(BRED, "Choice must be in %s range\n" % choices)
result = _interactive_traversal(expr, stage)
else:
result = _interactive_traversal(args[choice], stage + 1)
return result
return _interactive_traversal(expr, 0)
def ibin(n, bits=0, str=False):
"""Return a list of length ``bits`` corresponding to the binary value
of ``n`` with small bits to the right (last). If bits is omitted, the
length will be the number required to represent ``n``. If the bits are
desired in reversed order, use the [::-1] slice of the returned list.
If a sequence of all bits-length lists starting from [0, 0,..., 0]
through [1, 1, ..., 1] are desired, pass a non-integer for bits, e.g.
'all'.
If the bit *string* is desired pass ``str=True``.
Examples
========
>>> from sympy.utilities.iterables import ibin
>>> ibin(2)
[1, 0]
>>> ibin(2, 4)
[0, 0, 1, 0]
>>> ibin(2, 4)[::-1]
[0, 1, 0, 0]
If all lists corresponding to 0 to 2**n - 1, pass a non-integer
for bits:
>>> bits = 2
>>> for i in ibin(2, 'all'):
... print(i)
(0, 0)
(0, 1)
(1, 0)
(1, 1)
If a bit string is desired of a given length, use str=True:
>>> n = 123
>>> bits = 10
>>> ibin(n, bits, str=True)
'0001111011'
>>> ibin(n, bits, str=True)[::-1] # small bits left
'1101111000'
>>> list(ibin(3, 'all', str=True))
['000', '001', '010', '011', '100', '101', '110', '111']
"""
if not str:
try:
bits = as_int(bits)
return [1 if i == "1" else 0 for i in bin(n)[2:].rjust(bits, "0")]
except ValueError:
return variations(list(range(2)), n, repetition=True)
else:
try:
bits = as_int(bits)
return bin(n)[2:].rjust(bits, "0")
except ValueError:
return (bin(i)[2:].rjust(n, "0") for i in range(2**n))
def variations(seq, n, repetition=False):
"""Returns a generator of the n-sized variations of ``seq`` (size N).
``repetition`` controls whether items in ``seq`` can appear more than once;
Examples
========
variations(seq, n) will return N! / (N - n)! permutations without
repetition of seq's elements:
>>> from sympy.utilities.iterables import variations
>>> list(variations([1, 2], 2))
[(1, 2), (2, 1)]
variations(seq, n, True) will return the N**n permutations obtained
by allowing repetition of elements:
>>> list(variations([1, 2], 2, repetition=True))
[(1, 1), (1, 2), (2, 1), (2, 2)]
If you ask for more items than are in the set you get the empty set unless
you allow repetitions:
>>> list(variations([0, 1], 3, repetition=False))
[]
>>> list(variations([0, 1], 3, repetition=True))[:4]
[(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1)]
See Also
========
sympy.core.compatibility.permutations
sympy.core.compatibility.product
"""
if not repetition:
seq = tuple(seq)
if len(seq) < n:
return
for i in permutations(seq, n):
yield i
else:
if n == 0:
yield ()
else:
for i in product(seq, repeat=n):
yield i
def subsets(seq, k=None, repetition=False):
"""Generates all k-subsets (combinations) from an n-element set, seq.
A k-subset of an n-element set is any subset of length exactly k. The
number of k-subsets of an n-element set is given by binomial(n, k),
whereas there are 2**n subsets all together. If k is None then all
2**n subsets will be returned from shortest to longest.
Examples
========
>>> from sympy.utilities.iterables import subsets
subsets(seq, k) will return the n!/k!/(n - k)! k-subsets (combinations)
without repetition, i.e. once an item has been removed, it can no
longer be "taken":
>>> list(subsets([1, 2], 2))
[(1, 2)]
>>> list(subsets([1, 2]))
[(), (1,), (2,), (1, 2)]
>>> list(subsets([1, 2, 3], 2))
[(1, 2), (1, 3), (2, 3)]
subsets(seq, k, repetition=True) will return the (n - 1 + k)!/k!/(n - 1)!
combinations *with* repetition:
>>> list(subsets([1, 2], 2, repetition=True))
[(1, 1), (1, 2), (2, 2)]
If you ask for more items than are in the set you get the empty set unless
you allow repetitions:
>>> list(subsets([0, 1], 3, repetition=False))
[]
>>> list(subsets([0, 1], 3, repetition=True))
[(0, 0, 0), (0, 0, 1), (0, 1, 1), (1, 1, 1)]
"""
if k is None:
for k in range(len(seq) + 1):
for i in subsets(seq, k, repetition):
yield i
else:
if not repetition:
for i in combinations(seq, k):
yield i
else:
for i in combinations_with_replacement(seq, k):
yield i
def numbered_symbols(prefix='x', cls=None, start=0, *args, **assumptions):
"""
Generate an infinite stream of Symbols consisting of a prefix and
increasing subscripts.
Parameters
==========
prefix : str, optional
The prefix to use. By default, this function will generate symbols of
the form "x0", "x1", etc.
cls : class, optional
The class to use. By default, it uses Symbol, but you can also use Wild or Dummy.
start : int, optional
The start number. By default, it is 0.
Returns
=======
sym : Symbol
The subscripted symbols.
"""
if cls is None:
# We can't just make the default cls=C.Symbol because it isn't
# imported yet.
cls = C.Symbol
while True:
name = '%s%s' % (prefix, start)
yield cls(name, *args, **assumptions)
start += 1
def capture(func):
"""Return the printed output of func().
`func` should be a function without arguments that produces output with
print statements.
>>> from sympy.utilities.iterables import capture
>>> from sympy import pprint
>>> from sympy.abc import x
>>> def foo():
... print('hello world!')
...
>>> 'hello' in capture(foo) # foo, not foo()
True
>>> capture(lambda: pprint(2/x))
'2\\n-\\nx\\n'
"""
from sympy.core.compatibility import StringIO
import sys
stdout = sys.stdout
sys.stdout = file = StringIO()
try:
func()
finally:
sys.stdout = stdout
return file.getvalue()
def sift(seq, keyfunc):
"""
Sift the sequence, ``seq`` into a dictionary according to keyfunc.
OUTPUT: each element in expr is stored in a list keyed to the value
of keyfunc for the element.
Examples
========
>>> from sympy.utilities import sift
>>> from sympy.abc import x, y
>>> from sympy import sqrt, exp
>>> sift(range(5), lambda x: x % 2)
{0: [0, 2, 4], 1: [1, 3]}
sift() returns a defaultdict() object, so any key that has no matches will
give [].
>>> sift([x], lambda x: x.is_commutative)
{True: [x]}
>>> _[False]
[]
Sometimes you won't know how many keys you will get:
>>> sift([sqrt(x), exp(x), (y**x)**2],
... lambda x: x.as_base_exp()[0])
{E: [exp(x)], x: [sqrt(x)], y: [y**(2*x)]}
If you need to sort the sifted items it might be better to use
``ordered`` which can economically apply multiple sort keys
to a squence while sorting.
See Also
========
ordered
"""
m = defaultdict(list)
for i in seq:
m[keyfunc(i)].append(i)
return m
def take(iter, n):
"""Return ``n`` items from ``iter`` iterator. """
return [ value for _, value in zip(xrange(n), iter) ]
def dict_merge(*dicts):
"""Merge dictionaries into a single dictionary. """
merged = {}
for dict in dicts:
merged.update(dict)
return merged
def common_prefix(*seqs):
"""Return the subsequence that is a common start of sequences in ``seqs``.
>>> from sympy.utilities.iterables import common_prefix
>>> common_prefix(list(range(3)))
[0, 1, 2]
>>> common_prefix(list(range(3)), list(range(4)))
[0, 1, 2]
>>> common_prefix([1, 2, 3], [1, 2, 5])
[1, 2]
>>> common_prefix([1, 2, 3], [1, 3, 5])
[1]
"""
if any(not s for s in seqs):
return []
elif len(seqs) == 1:
return seqs[0]
i = 0
for i in range(min(len(s) for s in seqs)):
if not all(seqs[j][i] == seqs[0][i] for j in xrange(len(seqs))):
break
else:
i += 1
return seqs[0][:i]
def common_suffix(*seqs):
"""Return the subsequence that is a common ending of sequences in ``seqs``.
>>> from sympy.utilities.iterables import common_suffix
>>> common_suffix(list(range(3)))
[0, 1, 2]
>>> common_suffix(list(range(3)), list(range(4)))
[]
>>> common_suffix([1, 2, 3], [9, 2, 3])
[2, 3]
>>> common_suffix([1, 2, 3], [9, 7, 3])
[3]
"""
if any(not s for s in seqs):
return []
elif len(seqs) == 1:
return seqs[0]
i = 0
for i in range(-1, -min(len(s) for s in seqs) - 1, -1):
if not all(seqs[j][i] == seqs[0][i] for j in xrange(len(seqs))):
break
else:
i -= 1
if i == -1:
return []
else:
return seqs[0][i + 1:]
def prefixes(seq):
"""
Generate all prefixes of a sequence.
Examples
========
>>> from sympy.utilities.iterables import prefixes
>>> list(prefixes([1,2,3,4]))
[[1], [1, 2], [1, 2, 3], [1, 2, 3, 4]]
"""
n = len(seq)
for i in xrange(n):
yield seq[:i + 1]
def postfixes(seq):
"""
Generate all postfixes of a sequence.
Examples
========
>>> from sympy.utilities.iterables import postfixes
>>> list(postfixes([1,2,3,4]))
[[4], [3, 4], [2, 3, 4], [1, 2, 3, 4]]
"""
n = len(seq)
for i in xrange(n):
yield seq[n - i - 1:]
def topological_sort(graph, key=None):
r"""
Topological sort of graph's vertices.
Parameters
==========
``graph`` : ``tuple[list, list[tuple[T, T]]``
A tuple consisting of a list of vertices and a list of edges of
a graph to be sorted topologically.
``key`` : ``callable[T]`` (optional)
Ordering key for vertices on the same level. By default the natural
(e.g. lexicographic) ordering is used (in this case the base type
must implement ordering relations).
Examples
========
Consider a graph::
+---+ +---+ +---+
| 7 |\ | 5 | | 3 |
+---+ \ +---+ +---+
| _\___/ ____ _/ |
| / \___/ \ / |
V V V V |
+----+ +---+ |
| 11 | | 8 | |
+----+ +---+ |
| | \____ ___/ _ |
| \ \ / / \ |
V \ V V / V V
+---+ \ +---+ | +----+
| 2 | | | 9 | | | 10 |
+---+ | +---+ | +----+
\________/
where vertices are integers. This graph can be encoded using
elementary Python's data structures as follows::
>>> V = [2, 3, 5, 7, 8, 9, 10, 11]
>>> E = [(7, 11), (7, 8), (5, 11), (3, 8), (3, 10),
... (11, 2), (11, 9), (11, 10), (8, 9)]
To compute a topological sort for graph ``(V, E)`` issue::
>>> from sympy.utilities.iterables import topological_sort
>>> topological_sort((V, E))
[3, 5, 7, 8, 11, 2, 9, 10]
If specific tie breaking approach is needed, use ``key`` parameter::
>>> topological_sort((V, E), key=lambda v: -v)
[7, 5, 11, 3, 10, 8, 9, 2]
Only acyclic graphs can be sorted. If the input graph has a cycle,
then :py:exc:`ValueError` will be raised::
>>> topological_sort((V, E + [(10, 7)]))
Traceback (most recent call last):
...
ValueError: cycle detected
.. seealso:: http://en.wikipedia.org/wiki/Topological_sorting
"""
V, E = graph
L = []
S = set(V)
E = list(E)
for v, u in E:
S.discard(u)
if key is None:
key = lambda value: value
S = sorted(S, key=key, reverse=True)
while S:
node = S.pop()
L.append(node)
for u, v in list(E):
if u == node:
E.remove((u, v))
for _u, _v in E:
if v == _v:
break
else:
kv = key(v)
for i, s in enumerate(S):
ks = key(s)
if kv > ks:
S.insert(i, v)
break
else:
S.append(v)
if E:
raise ValueError("cycle detected")
else:
return L
def rotate_left(x, y):
"""
Left rotates a list x by the number of steps specified
in y.
Examples
========
>>> from sympy.utilities.iterables import rotate_left
>>> a = [0, 1, 2]
>>> rotate_left(a, 1)
[1, 2, 0]
"""
if len(x) == 0:
return []
y = y % len(x)
return x[y:] + x[:y]
def rotate_right(x, y):
"""
Right rotates a list x by the number of steps specified
in y.
Examples
========
>>> from sympy.utilities.iterables import rotate_right
>>> a = [0, 1, 2]
>>> rotate_right(a, 1)
[2, 0, 1]
"""
if len(x) == 0:
return []
y = len(x) - y % len(x)
return x[y:] + x[:y]
def multiset_combinations(m, n, g=None):
"""
Return the unique combinations of size ``n`` from multiset ``m``.
Examples
========
>>> from sympy.utilities.iterables import multiset_combinations
>>> from itertools import combinations
>>> [''.join(i) for i in multiset_combinations('baby', 3)]
['abb', 'aby', 'bby']
>>> def count(f, s): return len(list(f(s, 3)))
The number of combinations depends on the number of letters; the
number of unique combinations depends on how the letters are
repeated.
>>> s1 = 'abracadabra'
>>> s2 = 'banana tree'
>>> count(combinations, s1), count(multiset_combinations, s1)
(165, 23)
>>> count(combinations, s2), count(multiset_combinations, s2)
(165, 54)
"""
if g is None:
if type(m) is dict:
if n > sum(m.values()):
return
g = [[k, m[k]] for k in ordered(m)]
else:
m = list(m)
if n > len(m):
return
try:
m = multiset(m)
g = [(k, m[k]) for k in ordered(m)]
except TypeError:
m = list(ordered(m))
g = [list(i) for i in group(m, multiple=False)]
del m
if sum(v for k, v in g) < n or not n:
yield []
else:
for i, (k, v) in enumerate(g):
if v >= n:
yield [k]*n
v = n - 1
for v in range(min(n, v), 0, -1):
for j in multiset_combinations(None, n - v, g[i + 1:]):
rv = [k]*v + j
if len(rv) == n:
yield rv
def multiset_permutations(m, size=None, g=None):
"""
Return the unique permutations of multiset ``m``.
Examples
========
>>> from sympy.utilities.iterables import multiset_permutations
>>> from sympy import factorial
>>> [''.join(i) for i in multiset_permutations('aab')]
['aab', 'aba', 'baa']
>>> factorial(len('banana'))
720
>>> len(list(multiset_permutations('banana')))
60
"""
if g is None:
if type(m) is dict:
g = [[k, m[k]] for k in ordered(m)]
else:
m = list(ordered(m))
g = [list(i) for i in group(m, multiple=False)]
del m
do = [gi for gi in g if gi[1] > 0]
SUM = sum([gi[1] for gi in do])
if not do or size is not None and (size > SUM or size < 1):
if size < 1:
yield []
return
elif size == 1:
for k, v in do:
yield [k]
elif len(do) == 1:
k, v = do[0]
v = v if size is None else (size if size <= v else 0)
yield [k for i in range(v)]
elif all(v == 1 for k, v in do):
for p in permutations([k for k, v in do], size):
yield list(p)
else:
size = size if size is not None else SUM
for i, (k, v) in enumerate(do):
do[i][1] -= 1
for j in multiset_permutations(None, size - 1, do):
if j:
yield [k] + j
do[i][1] += 1