数字2出现的次数。python
时间: 2024-06-12 20:11:40 浏览: 82
第二题单词出现的次数.py
可以使用引用中的方法来统计数字2在给定列表中出现的次数。具体实现方法如下:
```
def count_num(lst, num):
left = 0
right = len(lst) - 1
left_idx = get_left_idx(lst, num, left, right)
right_idx = get_right_idx(lst, num, left, right)
if left_idx == -1 or right_idx == -1:
return 0
return right_idx - left_idx + 1
def get_left_idx(lst, num, left, right):
while left <= right:
mid = (left + right) // 2
if lst[mid] < num:
left = mid + 1
else:
right = mid - 1
if left < len(lst) and lst[left] == num:
return left
else:
return -1
def get_right_idx(lst, num, left, right):
while left <= right:
mid = (left + right) // 2
if lst[mid] <= num:
left = mid + 1
else:
right = mid - 1
if right >= 0 and lst[right] == num:
return right
else:
return -1
lst = [1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 10]
num = 2
count = count_num(lst, num)
print("数字2在列表中出现的次数为:", count)
```
输出结果为:数字2在列表中出现的次数为: 2。
阅读全文