2016-02-26 23 views
1

你能幫我解決這個python問題嗎?python:列表模式

編寫Python功能all_modes(l),需要一個非空 列表l和返回兩個一組的所有 模式及其頻率:

所以,這裏是我的代碼:

def all_modes(l): 
    d = {} 
    for c in l: 
     if c not in d: 
      d[c] = 1 
     else: 
      d[c] = d[c] + 1 
    return ({c},d[c]) 

這裏有一些它的運行,不幸的是這個輸出是錯誤的:

>>> all_modes([5, 6, 7, 5]) 
({5}, 2) 

>>> all_modes([5]) 
({5}, 1) 

>>> all_modes([5, 6, 7, 5, 6]) 
({5, 6}, 2) 

>>> all_modes([5, 6, 7, 8, 9]) 
({8, 9, 5, 6, 7}, 1) 

我該如何解決它?

+0

你可以解決的一件事:'d'是一個字典,它沒有'append'。完全構建完成後,您需要處理字典*。 – gil

+0

什麼是測試用例:你想要什麼或者你有什麼? –

回答

3

您忘記只返回發生次數最大的值(模式的關鍵)。像這樣的東西,也許?

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 
+0

謝謝!有用 – HIABCD

2

你已經返回了錯誤的東西。當你點擊你的返回聲明時,c只是列表中的最後一項。你已經返回了它的數量。

你要回去找字典中的最大值:

count_max = max([v for v in d.itervalues()]) 

,然後找出所有具有計數的列表值:

mode_list = [k for k,v in d.iteritems() if v == count_max] 

的程序是現在:

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]) 

輸出:

([5], 2) 
([5], 1) 
([5, 6], 2) 
([8, 9, 5, 6, 7], 1) 

這是你需要的嗎?

+0

這是更易於訪問的版本:請注意,您可以使用** collections.Counter **子類輕鬆構建原始字典。 – Prune

+0

謝謝!它的工作原理 – HIABCD