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
420 lines (361 loc) · 12.5 KB
/
itertools.py
File metadata and controls
420 lines (361 loc) · 12.5 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
# coding=utf-8
# Copyright (c) 2017, 2018, 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
self._current = iter(self._iterables[self._idx])
return self.__next__()
class starmap():
pass
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