等差数列和等比数列类。功能如下:
- 模拟无穷项数
- 获取任一项的值
- 跨步取项
class GeneralSequence:
def __init__(self, valueAt):
self.valueAt = valueAt
def __getitem__(self, index):
if isinstance(index, slice):
from itertools import islice
return islice(iter(self), index.start,
index.stop, index.step)
else:
return self.valueAt(index)
def __iter__(self):
from itertools import count
return map(self.valueAt, count())
class ArithmeticSequence(GeneralSequence):
def __init__(self, a, d):
valueAt = lambda n: a + n * d
GeneralSequence.__init__(self, valueAt)
class GeometricSequence(GeneralSequence):
def __init__(self, a, q):
valueAt = lambda n: a * q**n
GeneralSequence.__init__(self, valueAt)
GeneralSequence
__init__
持有通项公式。
__genitem__
分两种情况,
- 输入的
index
是切片时,用itertools.islice
跨步取项。 - 输入
index
是数字时,用通项公式算出该处的值。
__iter__
实现迭代协议,可以支持这样的用法:
for item in GeometricSequence(1, 2):
if item > 10000:
break
print(item, end=' ')
>> 1 2 4 8 16 32 64 128 256 512 1024 2048 4096 8192
因为itertools.count
不会抛出StopIteration
异常,需要手动跳出循环。
ArithmeticSequence和GeometricSequence
接收各自的参数,构造充当通项公式的valueAt
函数。
用例
an = ArithmeticSequence(10, 2)
it = iter(an)
for i in range(10):
print(next(it), end=' ')
>> 10 12 14 16 18 20 22 24 26 28
bn = ArithmeticSequence(-5, 3)
for i in range(10):
print(bn[i], end=' ')
>> -5 -2 1 4 7 10 13 16 19 22
cn = GeometricSequence(1, 2)
list(cn[100:140:5])
>>
[1267650600228229401496703205376,
40564819207303340847894502572032,
1298074214633706907132624082305024,
41538374868278621028243970633760768,
1329227995784915872903807060280344576,
42535295865117307932921825928971026432,
1361129467683753853853498429727072845824,
43556142965880123323311949751266331066368]