Python 统计数字出现次数:面向对象和异常处理实现
使用 Python 统计数字出现次数:面向对象和异常处理实现
本示例使用 Python 语言,演示如何统计给定范围内(L, R)所有整数中数字 '2' 出现的次数,并提供两种实现方式:面向对象和异常处理。
需求:
从键盘依次输入两个数 L 和 R(L<R),统计范围 [L, R] 内所有整数中数字 '2' 出现的次数。例如,给定范围 [2, 22],数字 '2' 在数 '2' 中出现 1 次,在数 '12' 中出现 1 次,在数 '20' 中出现 1 次,在数 '21' 中出现 1 次,在数 '22' 中出现 2 次,因此数字 '2' 在该范围内一共出现了 6 次。
实现方法:
- 面向对象实现:
class CountNum:
def __init__(self, L, R):
if L >= R:
raise ValueError('L must be less than R')
self.L = L
self.R = R
self.count = 0
def count_num(self):
for i in range(self.L, self.R + 1):
self.count += str(i).count('2')
return self.count
def write_result(self):
with open('result.txt', 'w') as f:
f.write(str(self.count))
if __name__ == '__main__':
L = int(input('Please input L: '))
R = int(input('Please input R: '))
count_num = CountNum(L, R)
count = count_num.count_num()
count_num.write_result()
print('The count of number 2 is:', count)
- 异常处理实现:
L = int(input('Please input L: '))
R = int(input('Please input R: '))
if L >= R:
raise ValueError('L must be less than R')
count = 0
for i in range(L, R + 1):
count += str(i).count('2')
with open('result.txt', 'w') as f:
f.write(str(count))
print('The count of number 2 is:', count)
代码说明:
- 面向对象实现:
- 定义
CountNum类,包含初始化方法__init__,计数方法count_num和写入结果方法write_result。 __init__方法验证 L 是否小于 R,若不满足则抛出ValueError异常。count_num方法遍历范围内的所有整数,统计每个整数中数字 '2' 出现的次数。write_result方法将最终的统计结果写入文件result.txt中。
- 定义
- 异常处理实现:
- 代码先验证 L 是否小于 R,若不满足则抛出
ValueError异常。 - 遍历范围内的所有整数,统计每个整数中数字 '2' 出现的次数。
- 将最终的统计结果写入文件
result.txt中。
- 代码先验证 L 是否小于 R,若不满足则抛出
总结:
以上代码展示了使用 Python 语言,通过面向对象和异常处理两种方式,实现统计给定范围内(L, R)所有整数中数字 '2' 出现的次数。两种方法都保证了代码的逻辑清晰,并处理了 L 大于 R 时抛出异常的情况。你可以根据实际情况选择最适合你的方法。
原文地址: https://www.cveoy.top/t/topic/j5b8 著作权归作者所有。请勿转载和采集!