我特別想將Transform and Conquer用于Python模式功能,并撰寫了以下版本,我認為基本上是正確的(如果我錯了,請糾正我)。但是,當有多種模式時,只給出一個,這在技術上對我來說似乎不正確,因為這個值是“a”模式而不是“the”模式。
你會如何建議修改函式來解決這個問題?
def mode_presort(arr):
arr.sort() # Array must be sorted before we apply the algorithm.
i = 1
mode_frequency = 0
while i < len(arr):
run_length = 1
run_value = arr[i]
while i run_length < len(arr) and arr[i run_length] == run_value:
run_length = 1
if run_length > mode_frequency:
mode_frequency = run_length
mode_value = run_value
i = run_length
return mode_value
arr = [1, 1, 1, 2, 2]
print(mode_presort(arr)) # Output: 1
arr = [1, 1, 2, 2]
print(mode_presort(arr)) # Output: 2
非常感謝任何幫助。
uj5u.com熱心網友回復:
您的代碼中有一個錯誤:i不應初始化為 1,而應初始化為 0。
要獲得多個結果,請讓您的函式始終回傳一個串列,即使只有一種模式。
然后,只需添加頻率等于您迄今為止發現的最大值的情況。因此該if塊應更改為:
if run_length > mode_frequency:
mode_frequency = run_length
mode_value = [run_value] # Make it a list
elif run_length == mode_frequency: # Also deal with this case
mode_value.append(run_value) # Add alternative to existing list of modes
像往常一樣,有些庫已經提供了模式功能,比如 Pandas:
import pandas as pd
def mode(arr):
return list(pd.Series(arr).mode())
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/446395.html
下一篇:如何更改C中的函式引數?
