计算指定范围内能整除的个数及总和
计算指定范围内能被3 和 7 整除的个数及总和
1、递归实现:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 def count_and_sum(start,end,a=0,b=0): 2 if start == end: 3 return a,b 4 5 if start%3 == 0 and start%7 == 0: 6 a += 1 7 b += start 8 9 return count_and_sum(start + 1 ,end,a,b) 10 11 counting,total_sum = count_and_sum(1,998) 12 print("个数是%d, 总和是%d"%(counting,total_sum ))
只能计算到998,否则RecursionError: maximum recursion depth exceeded in comparison
2、列表生成式实现
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 def count_and_sum(start=0,end=0): 2 3 num_list = [num for num in range(start,end + 1) if num % 3 == 0 and num % 7 ==0] 4 5 return len(num_list),sum(num_list ) 6 7 counting,total_sum = count_and_sum(1,14333345) 8 9 10 print("个数是%d, 总和是%d"%(counting,total_sum ))
3、生成器实现
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 def count_and_sum(start=0,end=0): 2 3 gen_num = (num for num in range(start,end + 1) if num % 3 == 0 and num % 7 ==0) 4 5 counting = total_sum = 0 6 7 for num in gen_num: 8 counting += 1 9 total_sum += num 10 return counting,total_sum 11 12 counting,total_sum = count_and_sum(1,14333345) 13 14 print("个数是%d, 总和是%d"%(counting,total_sum ))