如何在一堆数字中查找众数,如果没有重复的数字数就报错的代码
时间: 2023-04-02 12:03:08 浏览: 130
寻找众数代码(快速排序)
以下是一个在一堆数字中查找众数的 Python 代码,如果没有重复的数字则会报错:
```python
from collections import Counter
def find_mode(numbers):
counter = Counter(numbers)
modes = counter.most_common()
if len(modes) > 1 and modes[][1] == modes[1][1]:
return None
return modes[][]
numbers = [1, 2, 3, 4, 5, 5, 5, 6, 6, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9]
mode = find_mode(numbers)
if mode:
print(f"The mode of the numbers is {mode}")
else:
print("There is no mode for the numbers")
```
希望对您有所帮助。
阅读全文