def all_modes(l):
d = {}
for c in l:
if c not in d:
d[c] = 1
else:
d[c] = d[c] + 1
count_max = max([v for v in d.itervalues()])
mode_list = [k for k,v in d.iteritems() if v == count_max]
return (mode_list, count_max)
print all_modes([5, 6, 7, 5])
print all_modes([5])
print all_modes([5, 6, 7, 5, 6])
print all_modes([5, 6, 7, 8, 9])
from collections import defaultdict
def modes(l):
d = defaultdict(int)
for num in l:
d[num] += 1
m = max(d.values())
return {k for k, v in d.items() if v == m}, m
你还错东西了。当您点击return语句时,c只是列表中的最后一项。你已经把它和它的计数还给你了。在
您必须返回字典才能找到最大值:
然后找到具有该计数的所有列表值:
^{pr2}$项目现在是:
输出:
这就是你需要的吗?在
您忘记了只返回出现次数最大化的值(模式的关键)。可能是这样吧?在
相关问题 更多 >
编程相关推荐