|
1 | 1 | """ |
2 | 2 | Arithmetic progression class |
3 | 3 |
|
| 4 | +# BEGIN ARITPROG_CLASS_DEMO |
| 5 | +
|
| 6 | + >>> ap = ArithmeticProgression(0, 1, 3) |
| 7 | + >>> list(ap) |
| 8 | + [0, 1, 2] |
4 | 9 | >>> ap = ArithmeticProgression(1, .5, 3) |
5 | 10 | >>> list(ap) |
6 | 11 | [1.0, 1.5, 2.0, 2.5] |
| 12 | + >>> ap = ArithmeticProgression(0, 1/3, 1) |
| 13 | + >>> list(ap) |
| 14 | + [0.0, 0.3333333333333333, 0.6666666666666666] |
| 15 | + >>> from fractions import Fraction |
| 16 | + >>> ap = ArithmeticProgression(0, Fraction(1, 3), 1) |
| 17 | + >>> list(ap) |
| 18 | + [Fraction(0, 1), Fraction(1, 3), Fraction(2, 3)] |
| 19 | + >>> from decimal import Decimal |
| 20 | + >>> ap = ArithmeticProgression(0, Decimal('.1'), .3) |
| 21 | + >>> list(ap) |
| 22 | + [Decimal('0.0'), Decimal('0.1'), Decimal('0.2')] |
7 | 23 |
|
8 | | -
|
| 24 | +# END ARITPROG_CLASS_DEMO |
9 | 25 | """ |
10 | 26 |
|
11 | | -import array |
12 | | -from collections import abc |
13 | 27 |
|
| 28 | +# BEGIN ARITPROG_CLASS |
14 | 29 | class ArithmeticProgression: |
15 | 30 |
|
16 | | - def __init__(self, begin, step, end): |
| 31 | + def __init__(self, begin, step, end=None): # <1> |
17 | 32 | self.begin = begin |
18 | 33 | self.step = step |
19 | | - self.end = end |
20 | | - self._build() |
21 | | - |
22 | | - def _build(self): |
23 | | - self._numbers = array.array('d') |
24 | | - n = self.begin |
25 | | - while n < self.end: |
26 | | - self._numbers.append(n) |
27 | | - n += self.step |
| 34 | + self.end = end # None -> "infinite" series |
28 | 35 |
|
29 | 36 | def __iter__(self): |
30 | | - return ArithmeticProgressionIterator(self._numbers) |
31 | | - |
32 | | - |
33 | | -class ArithmeticProgressionIterator(abc.Iterator): |
34 | | - |
35 | | - def __init__(self, series): |
36 | | - self._series = series |
37 | | - self._index = 0 |
38 | | - |
39 | | - def __next__(self): |
40 | | - if self._index < len(self._series): |
41 | | - item = self._series[self._index] |
42 | | - self._index += 1 |
43 | | - return item |
44 | | - else: |
45 | | - raise StopIteration |
46 | | - |
47 | | - |
48 | | - |
| 37 | + result = type(self.begin + self.step)(self.begin) # <2> |
| 38 | + forever = self.end is None # <3> |
| 39 | + index = 0 |
| 40 | + while forever or result < self.end: # <4> |
| 41 | + yield result # <5> |
| 42 | + index += 1 |
| 43 | + result = self.begin + self.step * index # <6> |
| 44 | +# END ARITPROG_CLASS |
0 commit comments