結果不是5,不是哪里代碼寫錯,謝謝幫忙糾錯
求數組中出現頻率最多的數 出錯,請各位幫忙查看,非常感謝
111111111111111Q
2016-07-07 12:11:40
TA貢獻165條經驗 獲得超90個贊
第一次迭代就返回 ,所以這個函數返回的就是 第一個元素了。
Python中有 現成的模塊做這個,下面代碼:
import?collections data?=?[1,2,5,10,-20,5,5] most_common_elem?=?collections.Counter(data).most_common() ##?下面懶得寫了。。。?從返回結果中?挑選?元素吧。。。
解釋:可以查看 Counter 的help 信息。
如果自己定義這個函數的話:
data?=?[1,2,5,10,-20,5,5] def?most_common(data): ????if?not?data: ????????return?data ????counter_sort?=?sorted(map(lambda?x:(data.count(x),x),set(data))) ????most_num?=?counter_sort[-1][0] ????return?list(map(lambda?x:x[-1],filter(lambda?x:x[0]?==?most_num,counter_sort))) ???? ##?用推導式再試試。。。 def?most_common(data): ????if?not?data: ????????return?data ????counter_sort?=?sorted([(data.count(x),x)?for?x?in?set(data)]) ????most_num?=?counter_sort[-1][0] ????return?[x[-1]?for?x?in?counter_sort?if?x[0]?==?most_num]
沒有做 太多的 參數檢查,下午有點困。就這樣吧。。。
舉報