1 class ArithmeticProgression: 2 3 def __init__(self, begin, step, end = None): 4 self.begin = begin 5 self.end = end 6 self.step = step 7 8 9 def __iter__(self): 10 result = type(self.begin + self.step)(self.begin) 11 forever = self.end is None 12 index = 0 13 14 while forever or result < self.end: 15 yield result 16 index += 1 17 result = self.begin + self.step * index 18 19 20 21 22 ap = list(ArithmeticProgression(0,1,3)) 23 print('\n', ap) 24 25 26 ap1 = list(ArithmeticProgression(1, 0.5, 3)) 27 print('\n', ap1) 28 29 30 ap2 = list(ArithmeticProgression(1, 1/3, 4)) 31 print('\n', ap2) 32 33 34 from fractions import Fraction 35 ap3 = list(ArithmeticProgression(1, Fraction(2,3),4)) 36 print('\n', ap3) 37 38 39 from decimal import Decimal 40 ap4 = list(ArithmeticProgression(1, Decimal('.8'), 6)) 41 print('\n', ap4) 42 43 44 45 46 #定义成函数形式实现上述功能_生成器函数 47 def aritprog_gen(begin, step, end = None): 48 result = type(begin + step)(begin) 49 forever = end is None 50 index = 0 51 52 while forever or result < end: 53 yield result 54 index += 1 55 result = begin + step * index 56 57 58 59 60 61 62 #使用函数实现的第二种方式: 63 import itertools 64 65 def aritpro_gen_v2(begin, step, end = None): 66 first = type(begin + step)(begin) 67 ap_gen = itertools.count(begin, step) 68 69 if end is None: 70 itertools.takewhile(lambda n: n < end, ap_gen) 71 72 return ap_gen
标签:begin,end,self,生成器,step,ArithmeticProgression,result,等差数列 From: https://www.cnblogs.com/bravesunforever/p/17453394.html