forked from oracle/graalpython
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathitertools.py
More file actions
738 lines (623 loc) · 21.9 KB
/
itertools.py
File metadata and controls
738 lines (623 loc) · 21.9 KB
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
# coding=utf-8
# Copyright (c) 2017, 2019, Oracle and/or its affiliates.
# Copyright (c) 2017, The PyPy Project
#
# The MIT License
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation
# files (the "Software"), to deal in the Software without
# restriction, including without limitation the rights to use,
# copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
class repeat():
def __init__(self, obj, times=None):
self.obj = obj
self.times = times
self.step = 0
def __iter__(self):
return self
def __next__(self):
if self.times is not None:
if self.step >= self.times:
raise StopIteration
else:
self.step += 1
return self.obj
class chain():
"""
Return a chain object whose .__next__() method returns elements from the
first iterable until it is exhausted, then elements from the next
iterable, until all of the iterables are exhausted.
"""
def __init__(self, *iterables):
self._iterables = iterables
self._len = len(iterables)
if self._len > 0:
self._current = iter(self._iterables[0])
self._idx = 0
def __iter__(self):
return self
def __next__(self):
if self._idx >= self._len:
raise StopIteration
try:
return next(self._current)
except (StopIteration, IndexError):
self._idx += 1
if self._idx >= self._len:
raise StopIteration
self._current = iter(self._iterables[self._idx])
return self.__next__()
@classmethod
def from_iterable(cls, arg):
return cls(*iter(arg))
class starmap():
"""starmap(function, sequence) --> starmap object
Return an iterator whose values are returned from the function evaluated
with an argument tuple taken from the given sequence.
"""
def __init__(self, fun, iterable):
self.fun = fun
self.iterable = iter(iterable)
def __iter__(self):
return self
def __next__(self):
obj = next(self.iterable)
return self.fun(*obj)
class islice(object):
def __init__(self, iterable, *args):
self._iterable = enumerate(iter(iterable))
self._indexes = iter(range(*args))
def __iter__(self):
return self
def __next__(self):
index = next(self._indexes) # may raise StopIteration
while True:
i, element = next(self._iterable) # may raise StopIteration
if i == index:
return element
class count(object):
def __init__(self, start=0, step=1):
if not isinstance(start, (int, float)) or \
not isinstance(step, (int, float)):
raise TypeError('a number is required')
self._cnt = start
self._step = step
def __next__(self):
_cnt = self._cnt
self._cnt += self._step
return _cnt
def __repr__(self):
_repr = 'count({}'.format(self._cnt)
if not isinstance(self._step, int) or self._step != 1:
_repr += ', {}'.format(self._step)
return _repr + ')'
class permutations():
"""permutations(iterable[, r]) --> permutations object
Return successive r-length permutations of elements in the iterable.
permutations(range(3), 2) --> (0,1), (0,2), (1,0), (1,2), (2,0), (2,1)
"""
def __init__(self, iterable, r = None):
self.pool = iterable
if r is None:
self.r = len(iterable)
else:
self.r = r
n = len(iterable)
n_minus_r = n - self.r
if n_minus_r < 0:
self.stopped = self.raised_stop_iteration = True
else:
self.stopped = self.raised_stop_iteration = False
self.indices = list(range(n))
self.cycles = list(range(n, n_minus_r, -1))
self.started = False
def __iter__(self):
return self
def __next__(self):
if self.stopped:
self.raised_stop_iteration = True
raise StopIteration
r = self.r
indices = self.indices
result = tuple([self.pool[indices[i]] for i in range(r)])
cycles = self.cycles
i = r - 1
while i >= 0:
j = cycles[i] - 1
if j > 0:
cycles[i] = j
indices[i], indices[-j] = indices[-j], indices[i]
return result
cycles[i] = len(indices) - i
n1 = len(indices) - 1
assert n1 >= 0
num = indices[i]
for k in range(i, n1):
indices[k] = indices[k+1]
indices[n1] = num
i -= 1
self.stopped = True
if self.started:
raise StopIteration
else:
self.started = True
return result
def __reduce__(self):
if self.raised_stop_iteration:
pool = []
else:
pool = self.pool
result = [
type(self),
tuple([
tuple(pool), self.r
])
]
if not self.raised_stop_iteration:
# we must pickle the indices and use them for setstate
result = result + [
tuple([
tuple(self.indices),
tuple(self.cycles),
self.started,
])]
return tuple(result)
def __setstate__(self, state):
state = list(state)
if len(state) == 3:
indices, cycles, started = state
indices = list(indices)
cycles = list(cycles)
self.started = bool(started)
else:
raise ValueError("invalid arguments")
if len(indices) != len(self.pool) or len(cycles) != self.r:
raise ValueError("invalid arguments")
n = len(self.pool)
for i in range(n):
index = indices[i]
if index < 0:
index = 0
elif index > n-1:
index = n-1
self.indices[i] = index
for i in range(self.r):
index = cycles[i]
if index < 1:
index = 1
elif index > n-i:
index = n-i
self.cycles[i] = index
class product():
"""Cartesian product of input iterables.
Equivalent to nested for-loops in a generator expression. For example,
``product(A, B)`` returns the same as ``((x,y) for x in A for y in B)``.
The nested loops cycle like an odometer with the rightmost element advancing
on every iteration. This pattern creates a lexicographic ordering so that if
the input's iterables are sorted, the product tuples are emitted in sorted
order.
To compute the product of an iterable with itself, specify the number of
repetitions with the optional *repeat* keyword argument. For example,
``product(A, repeat=4)`` means the same as ``product(A, A, A, A)``.
This function is equivalent to the following code, except that the
actual implementation does not build up intermediate results in memory::
def product(*args, **kwds):
# product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
# product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111
pools = map(tuple, args) * kwds.get('repeat', 1)
result = [[]]
for pool in pools:
result = [x+[y] for x in result for y in pool]
for prod in result:
yield tuple(prod)
"""
def __init__(self, *args, repeat=1):
self.gears = [list(arg) for arg in args] * repeat
for gear in self.gears:
if len(gear) == 0:
self.indices = None
self.lst = None
self.stopped = True
break
else:
self.indices = [0] * len(self.gears)
self.lst = None
self.stopped = False
def _rotate_previous_gears(self):
lst = self.lst
x = len(self.gears) - 1
lst[x] = self.gears[x][0]
self.indices[x] = 0
x -= 1
# the outer loop runs as long as a we have a carry
while x >= 0:
gear = self.gears[x]
index = self.indices[x] + 1
if index < len(gear):
# no carry: done
lst[x] = gear[index]
self.indices[x] = index
return
lst[x] = gear[0]
self.indices[x] = 0
x -= 1
else:
self.lst = None
self.stopped = True
def fill_next_result(self):
# the last gear is done here, in a function with no loop,
# to allow the JIT to look inside
if self.lst is None:
self.lst = [None for gear in self.gears]
for index, gear in enumerate(self.gears):
self.lst[index] = gear[0]
return
lst = self.lst
x = len(self.gears) - 1
if x >= 0:
gear = self.gears[x]
index = self.indices[x] + 1
if index < len(gear):
# no carry: done
lst[x] = gear[index]
self.indices[x] = index
else:
self._rotate_previous_gears()
else:
self.stopped = True
def __iter__(self):
return self
def __next__(self):
if not self.stopped:
self.fill_next_result()
if self.stopped:
raise StopIteration
return tuple(self.lst)
def __reduce__(self):
if not self.stopped:
gears = [tuple(gear) for gear in self.gears]
result = [
type(self),
tuple(gears)
]
if self.lst is not None:
result = result + [tuple(self.indices)]
else:
result = [
type(self),
tuple([tuple([])])
]
return tuple(result)
def __setstate__(self, state):
gear_count = len(self.gears)
indices = list(state)
lst = []
for i, gear in enumerate(self.gears):
index = indices[i]
gear_size = len(gear)
if self.indices is None or gear_size == 0:
self.stopped = True
return
if index < 0:
index = 0
if index > gear_size - 1:
index = gear_size - 1
self.indices[i] = index
lst.append(gear[index])
self.lst = lst
class accumulate(object):
"""
"accumulate(iterable) --> accumulate object
Return series of accumulated sums."""
def __init__(self, iterable, func=None):
self.iterable = iter(iterable)
self.func = func
self.total = None
def __iter__(self):
return self
def __next__(self):
value = next(self.iterable)
if self.total is None:
self.total = value
return value
if self.func is None:
self.total += value
else:
self.total = self.func(total, value)
return self.total
class dropwhile(object):
"""
dropwhile(predicate, iterable) --> dropwhile object
Drop items from the iterable while predicate(item) is true.
Afterwards, return every element until the iterable is exhausted.
"""
def __init__(self, predicate, iterable):
self.predicate = predicate
self.iterable = iter(iterable)
self.done_dropping = False
def __iter__(self):
return self
def __next__(self):
while not self.done_dropping:
n = next(self.iterable)
if self.predicate(n):
continue
else:
self.done_dropping = True
return n
return next(self.iterable)
class filterfalse(object):
"""
filterfalse(function or None, sequence) --> filterfalse object
Return those items of sequence for which function(item) is false.
If function is None, return the items that are false.
"""
def __init__(self, func, sequence):
self.func = func or (lambda x: False)
self.iterator = iter(sequence)
def __iter__(self):
return self
def __next__(self):
while True:
n = next(self.iterator)
if not self.func(n):
return n
class takewhile(object):
"""Make an iterator that returns elements from the iterable as
long as the predicate is true.
Equivalent to :
def takewhile(predicate, iterable):
for x in iterable:
if predicate(x):
yield x
else:
break
"""
def __init__(self, predicate, iterable):
self._predicate = predicate
self._iter = iter(iterable)
def __iter__(self):
return self
def __next__(self):
value = next(self._iter)
if not self._predicate(value):
self._iter = iter([])
raise StopIteration()
return value
class groupby(object):
"""Make an iterator that returns consecutive keys and groups from the
iterable. The key is a function computing a key value for each
element. If not specified or is None, key defaults to an identity
function and returns the element unchanged. Generally, the
iterable needs to already be sorted on the same key function.
The returned group is itself an iterator that shares the
underlying iterable with groupby(). Because the source is shared,
when the groupby object is advanced, the previous group is no
longer visible. So, if that data is needed later, it should be
stored as a list:
groups = []
uniquekeys = []
for k, g in groupby(data, keyfunc):
groups.append(list(g)) # Store group iterator as a list
uniquekeys.append(k)
"""
def __init__(self, iterable, key=None):
self._iterator = iter(iterable)
self._keyfunc = key
self._tgtkey = self._currkey = self._currvalue = None
def __iter__(self):
return self
def __next__(self):
self._skip_to_next_iteration_group()
key = self._tgtkey = self._currkey
grouper = _groupby(self, key)
return (key, grouper)
def _skip_to_next_iteration_group(self):
while True:
if self._currkey is None:
pass
elif self._tgtkey is None:
break
else:
if not self._tgtkey == self._currkey:
break
newvalue = next(self._iterator)
if self._keyfunc is None:
newkey = newvalue
else:
newkey = self._keyfunc(newvalue)
self._currkey = newkey
self._currvalue = newvalue
class _groupby():
def __init__(self, groupby, tgtkey):
self.groupby = groupby
self.tgtkey = tgtkey
def __iter__(self):
return self
def __next__(self):
groupby = self.groupby
if groupby._currvalue is None:
newvalue = next(groupby._iterator)
if groupby._keyfunc is None:
newkey = newvalue
else:
newkey = groupby._keyfunc(newvalue)
assert groupby._currvalue is None
groupby._currkey = newkey
groupby._currvalue = newvalue
assert groupby._currkey is not None
if not self.tgtkey == groupby._currkey:
raise StopIteration(None)
result = groupby._currvalue
groupby._currvalue = None
groupby._currkey = None
return result
class combinations():
"""
combinations(iterable, r) --> combinations object
Return successive r-length combinations of elements in the iterable.
combinations(range(4), 3) --> (0,1,2), (0,1,3), (0,2,3), (1,2,3)
"""
def __init__(self, pool, indices, r):
self.pool = pool
self.indices = indices
if r < 0:
raise ValueError("r must be non-negative")
self.r = r
self.last_result = None
self.stopped = r > len(pool)
def get_maximum(self, i):
return i + len(self.pool) - self.r
def max_index(self, j):
return self.indices[j - 1] + 1
def __iter__(self):
return self
def __next__(self):
if self.stopped:
raise StopIteration
if self.last_result is None:
# On the first pass, initialize result tuple using the indices
result = [None] * self.r
for i in range(self.r):
index = self.indices[i]
result[i] = self.pool[index]
else:
# Copy the previous result
result = self.last_result[:]
# Scan indices right-to-left until finding one that is not at its
# maximum
i = self.r - 1
while i >= 0 and self.indices[i] == self.get_maximum(i):
i -= 1
# If i is negative, then the indices are all at their maximum value
# and we're done
if i < 0:
self.stopped = True
raise StopIteration
# Increment the current index which we know is not at its maximum.
# Then move back to the right setting each index to its lowest
# possible value
self.indices[i] += 1
for j in range(i + 1, self.r):
self.indices[j] = self.max_index(j)
# Update the result for the new indices starting with i, the
# leftmost index that changed
for i in range(i, self.r):
index = self.indices[i]
elem = self.pool[index]
result[i] = elem
self.last_result = result
return tuple(result)
class combinations_with_replacement(combinations):
"""
combinations_with_replacement(iterable, r) --> combinations_with_replacement object
Return successive r-length combinations of elements in the iterable
allowing individual elements to have successive repeats.
combinations_with_replacement('ABC', 2) --> AA AB AC BB BC CC
"""
def __init__(self, iterable, r):
pool = list(iterable)
if r < 0:
raise ValueError("r must be non-negative")
indices = [0] * r
super().__init__(pool, indices, r)
self.stopped = len(pool) == 0 and r > 0
def get_maximum(self, i):
return len(self.pool) - 1
def max_index(self, j):
return self.indices[j - 1]
class zip_longest():
"""
zip_longest(iter1 [,iter2 [...]], [fillvalue=None]) --> zip_longest object
Return a zip_longest object whose .next() method returns a tuple where
the i-th element comes from the i-th iterable argument. The .next()
method continues until the longest iterable in the argument sequence
is exhausted and then it raises StopIteration. When the shorter iterables
are exhausted, the fillvalue is substituted in their place. The fillvalue
defaults to None or can be specified by a keyword argument.
"""
def __iter__(self):
return self
def _fetch(self, index):
it = self.iterators[index]
if it is not None:
try:
return next(it)
except StopIteration:
self.active -= 1
if self.active <= 0:
# It was the last active iterator
raise
self.iterators[index] = None
return self.fillvalue
def __next__(self):
if self.active <= 0:
raise StopIteration
nb = len(self.iterators)
if nb == 0:
raise StopIteration
result = []
for index in range(nb):
result.append(self._fetch(index))
return tuple(result)
def __new__(subtype, iter1, *args, fillvalue=None):
self = object.__new__(subtype)
self.fillvalue = fillvalue
self.active = len(args) + 1
self.iterators = [iter(iter1)] + [iter(arg) for arg in args]
return self
class cycle():
"""
Make an iterator returning elements from the iterable and
saving a copy of each. When the iterable is exhausted, return
elements from the saved copy. Repeats indefinitely.
Equivalent to :
def cycle(iterable):
saved = []
for element in iterable:
yield element
saved.append(element)
while saved:
for element in saved:
yield element
"""
def __init__(self, iterable):
self.saved = []
self.iterable = iter(iterable)
self.index = 0
def __iter__(self):
return self
def __next__(self):
if self.index > 0:
if not self.saved:
raise StopIteration
if len(self.saved) > self.index:
obj = self.saved[self.index]
self.index += 1
else:
obj = self.saved[0]
self.index = 1
else:
try:
obj = next(self.iterable)
except StopIteration:
if not self.saved:
raise
obj = self.saved[0]
self.index = 1
else:
self.saved.append(obj)
return obj