python 整数中1出现的次数

把整数转换为字符串

用count计数

 1 # -*- coding:utf-8 -*-
 2 class Solution:
 3     def NumberOf1Between1AndN_Solution(self, n):
 4         # write code here
 5         count = 0
 6         for i in range(1,n+1):
 7             s = str(i)
 8             count += s.count('1')
 9         return count
10         

 

转载于:https://www.cnblogs.com/shunyu/p/8545519.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 答案是:最多的数字可以通过使用Python的内置函数collections.Counter()来获取。可以使用 Python 内置的函数 max() 来找到一个整数序列出现最多的数。以下是一个示例代码: ```python numbers = [1, 3, 2, 1, 5, 2, 2, 4, 2] most_common_number = max(set(numbers), key=numbers.count) print(most_common_number) ``` 这个代码首先使用 set() 函数去重,然后使用 count() 函数计算每个元素在序列出现次数,最后使用 max() 函数找到出现次数最多的元素。在这个例子,输出结果是 2,因为数字 2 出现了 4 次,是这个序列出现最多的数。 ### 回答2: 要求寻找整数序列出现次数最多的数,可以用 Python 的 Counter 类。这个类可以帮助统计序列每个元素出现次数。具体步骤如下: 1. 导入 Counter 类。 ``` from collections import Counter ``` 2. 输入整数序列。 ``` nums = [1, 2, 3, 1, 2, 1, 4, 5, 5, 6] ``` 3. 使用 Counter 类统计数字出现次数。 ``` count = Counter(nums) ``` 4. 找出出现次数最多的数字。 ``` most_common = count.most_common(1) ``` `most_common()` 方法可以返回序列出现次数最多的元素及其出现次数。在这里,我们设定参数为 1,即返回出现次数最多的单个元素。如果需要返回多个元素,可以将参数设定为需要的数量。 5. 输出结果。 ``` print(most_common[0][0]) ``` 以上步骤就是使用 Python 寻找整数序列出现次数最多的数的方法。你只需要将输入的整数序列替换为你想要处理的序列即可。 ### 回答3: 问题描述: 给定一个整数序列,编写一个Python函数,求出这个整数序列出现次数最多的数。 思路分析: 为了实现对整数序列出现次数最多的数的求解,可以通过以下步骤来完成: 1. 定义一个空的字典,用来保存每个数字在序列出现次数。 2. 遍历整数序列,对于序列的每个数字,都在字典对应的位置上进行加1操作。 3. 通过遍历字典,找出其出现次数最多的数字,并记录下来。 4. 返回出现次数最多的数字。 Python代码: def count_most_occurence(nums): counts = {} for num in nums: if num in counts: counts[num] += 1 else: counts[num] = 1 max_count = 0 max_num = None for num, count in counts.items(): if count > max_count: max_count = count max_num = num return max_num 测试: nums = [1, 3, 5, 5, 5, 7, 9, 9] print(count_most_occurence(nums)) # 输出:5 nums = [1, 2, 3, 4, 5, 6] print(count_most_occurence(nums)) # 输出:1
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值