Python 实现数字统计:从 M 到 N 的数字出现次数
class NumberStatistics:
def __init__(self, m, n):
self.m = m
self.n = n
self.count = [0] * 10 # 存放 0~9 出现的个数
def solve(self):
for i in range(self.m, self.n + 1):
for c in str(i):
self.count[int(c)] += 1
def print_result(self):
print(' '.join(map(str, self.count)))
m, n = map(int, input().split())
ns = NumberStatistics(m, n)
ns.solve()
ns.print_result()
本文介绍了如何使用 Python 类来统计给定范围内每个数字出现的次数。代码简单易懂,使用循环和列表来实现统计功能。希望这篇文章能帮助您理解 Python 类和数字统计的基本概念。
代码示例:
假设输入为 129 137,程序将输出 1 10 2 9 1 1 1 1 0 1,表示数字 0 出现 1 次,数字 1 出现 10 次,数字 2 出现 2 次,以此类推。
您可以通过以下方式使用该代码:
- 将代码复制到 Python 文件中。
- 运行 Python 文件。
- 输入两个整数 M 和 N,用空格分隔。
- 程序将输出每个数字出现的次数。
原文地址: https://www.cveoy.top/t/topic/nvve 著作权归作者所有。请勿转载和采集!