读用Python编程语言实现下列任务 从键盘依次输入两个数L和 RLR 请统计范围LR的所有整数中数字2出现的火数。 比如给定范围222数字2在数2中出现了1次在数12中出现1次在数20中出现1次在数21中出现1次在数22中出现2次所以数字2在该范围内一共出现了6次。 1请读用面向对象按术完成上述任务; 2当 LR 时抛出ValueError或AssertionError ; 3将统计结果写入文件
- 面向对象实现:
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
原文地址: https://www.cveoy.top/t/topic/cEsX 著作权归作者所有。请勿转载和采集!