ch17: update from book draft

This commit is contained in:
Luciano Ramalho
2020-02-18 23:45:05 -03:00
parent 70650841b3
commit aa868e8f75
35 changed files with 788 additions and 31 deletions

View File

@@ -1,7 +1,7 @@
"""
Arithmetic progression class
# BEGIN ARITPROG_CLASS_DEMO
# tag::ARITPROG_CLASS_DEMO[]
>>> ap = ArithmeticProgression(0, 1, 3)
>>> list(ap)
@@ -21,24 +21,25 @@ Arithmetic progression class
>>> list(ap)
[Decimal('0.0'), Decimal('0.1'), Decimal('0.2')]
# END ARITPROG_CLASS_DEMO
# end::ARITPROG_CLASS_DEMO[]
"""
# BEGIN ARITPROG_CLASS
# tag::ARITPROG_CLASS[]
class ArithmeticProgression:
def __init__(self, begin, step, end=None): # <1>
def __init__(self, begin, step, end=None): # <1>
self.begin = begin
self.step = step
self.end = end # None -> "infinite" series
def __iter__(self):
result = type(self.begin + self.step)(self.begin) # <2>
forever = self.end is None # <3>
result_type = type(self.begin + self.step) # <2>
result = result_type(self.begin) # <3>
forever = self.end is None # <4>
index = 0
while forever or result < self.end: # <4>
yield result # <5>
while forever or result < self.end: # <5>
yield result # <6>
index += 1
result = self.begin + self.step * index # <6>
# END ARITPROG_CLASS
result = self.begin + self.step * index # <7>
# end::ARITPROG_CLASS[]