输入一个正整数n,检查n中重复出现的数字,并打印出一份列表,显示每个数字在正整数n中出现的次数。
时间: 2023-03-20 08:04:50 浏览: 96
可以使用字典来记录每个数字出现的次数,遍历正整数n的每一位数字,如果该数字已经在字典中出现过,则将其对应的计数器加1,否则将其加入字典并初始化计数器为1。最后遍历字典,输出每个数字及其出现次数即可。
示例代码:
n = int(input("请输入一个正整数:"))
count = {}
while n > :
digit = n % 10
if digit in count:
count[digit] += 1
else:
count[digit] = 1
n //= 10
print("重复出现的数字及其出现次数:")
for digit, cnt in count.items():
if cnt > 1:
print("{}: {}".format(digit, cnt))
相关问题
python输入一个正整数N,检查N中重复出现的数字,并打印出一份列表,显示每个数字在正整数N中出现的次数。
可以通过将正整数N转换为字符串,再遍历字符串中的每个字符,使用Python的字典来统计每个数字出现的次数。最后,遍历字典,打印出现次数大于1的数字以及它们在正整数N中出现的次数。
以下是一个示例代码:
```python
n = input("请输入一个正整数N:")
count_dict = {}
for digit in n:
if digit in count_dict:
count_dict[digit] += 1
else:
count_dict[digit] = 1
print("重复出现的数字及其出现次数:")
for digit, count in count_dict.items():
if count > 1:
print(digit + "出现了" + str(count) + "次")
```
示例输入:
```
请输入一个正整数N:123456789987654321
```
输出结果:
```
重复出现的数字及其出现次数:
1出现了1次
2出现了2次
3出现了2次
4出现了2次
5出现了2次
6出现了2次
7出现了1次
8出现了2次
9出现了2次
```
py输入一个正整数N,检查N中重复出现的数字,并打印出一份列表,显示每个数字在正整数N中出现的次数。
好的,这里是 Python 代码实现:
```python
def find_duplicates(n):
digits = str(n)
counter = {}
for digit in digits:
if digit in counter:
counter[digit] += 1
else:
counter[digit] = 1
duplicates = [digit for digit in counter if counter[digit] > 1]
for digit in duplicates:
print(f"{digit} appears {counter[digit]} times in {n}.")
# 测试
find_duplicates(123456789)
```
函数 `find_duplicates(n)` 接受一个正整数 `n`,将其转化为字符串 `digits`,使用字典 `counter` 统计每个数字出现的次数,然后将出现次数大于 1 的数字存入列表 `duplicates` 中,并输出每个重复出现的数字在 `n` 中出现的次数。
在主程序中调用函数 `find_duplicates(n)`,传入测试数据进行测试。
相关推荐
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)