需求:
实现一个连续浮点数发生器FloatRange和(range类似),根据给定的范围(start,end)和步进值(step)产生一些列连续浮点数,如迭代FloatRange(3.0,4.0,0.2)可产生序列:
正向:3.0-->3.2-->3.4-->3.6-->3.8-->4.0
反向:4.0-->3.8-->3.6-->3.4-->3.2-->3.0
思路:
实现反向迭代协议的__reversed__方法,它返回一个反向迭代器。
代码:
class FloatRange:
def __init__(self,start,end,step=0.1):
self.start = start
self.end = end
self.step = step
def __iter__(self):
t = self.start
while t <= self.end:
yield t
t += self.step
def __reversed__(self):
t = self.end
while t >= self.start:
yield t
t -= self.step
if __name__=='__main__':
for x in reversed(FloatRange(1.0,4.0,0.5)):
print(x)
====================================================
from decimal import Decimal
class FloatRange:
def __init__(self,a,b,step):
self.a = Decimal(str(a)) # 此处是为了消除10进制和2进制浮点数转换中的误差
self.b = Decimal(str(b))
self.step = Decimal(str(step))
def __iter__(self):
t = self.a
while t <= self.b:
yield float(t) # 将字符串类型转换成浮点数的类型
t += self.step
def __reversed__(self):
t = self.b
while t >= self.a:
yield float(t)
t -= self.step
fr = FloatRange(3.0,4.0,0.2)
for x in fr:
print(x)
print('-' * 20)
for x in reversed(fr):
print(x)
=========================================================
>>> l = [1,2,3,4,5]
>>> l.reverse()
>>> l
[5, 4, 3, 2, 1]
>>> l[::-1]
[1, 2, 3, 4, 5]
>>> l = [1,2,3,4,5]
>>> reversed(l)
<list_reverseiterator at 0x7fafb4cccc50>
>>> iter(l)
<list_iterator at 0x7fafaf4c3e48>
>>> for x in reversed(l):
... print(x)
...
5
4
3
2
1
>>> d = {}
>>> reversed(d)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-10-b13b185f39f7> in <module>
----> 1 reversed(d)
TypeError: 'dict' object is not reversible
>>> s = 'abc'
>>> reversed(s)
<reversed at 0x7fafaf700cc0>
>>> from decimal import Decimal
>>> Decimal('0.2')
Decimal('0.2')
>>> from functools import reduce
>>> reduce(Decimal.__add__,[Decimal('0.2')] * 5)
Decimal('1.0')
>>> reduce(Decimal.__add__,[Decimal('0.2')] * 30)
Decimal('6.0')
>>> Decimal(0.2)
Decimal('0.200000000000000011102230246251565404236316680908203125')
>>> Decimal('0.2') > Decimal('0.1')
True
>>>