リストを呼び出すと、関数は 4.5 ではなく中央値として 4.0 を出力し続けます [4, 5, 4, 5]


これまでの私のコードは次のとおりです。

# x is the users input sorted, use x as parameter
# a is the index of the middle number in the odd version of x
# b is the 1st of the indexs in the even version of x
# d is the result of the 2 middle numbers
# being added together in the even version of x

def median(lst):

    x = sorted(lst)

    if len(x) % 2 != 0:
        # If the users input is odd
        a = len(x) // 2
        return(x[a])

    elif len(x) % 2 == 0:
        # If the users input is even
        b = len(x) // 2 - 1
        c = len(x) // 2
        d = (x[b] + x[c])
        ev_median = (d / 2)
        return(float(ev_median))

print(median([4, 5, 4, 5]))

どうすればいいのか説明してもらえますか? ありがとう。

私が試したこと:

フロア分割の代わりに通常の分割を使用して、さまざまな異なるインデックスを使用します。

解決策 1

中央値の定義を読んでください。

データセットに偶数の観測値がある場合、明確な中間値は存在せず、中央値は通常、2 つの中間値の算術平均として定義されます。

コードはそれを行いません。データセットの外側にある 2 つの値を取り、それらを平均して結果を取得します。 インデックスは 0 から始まるため、4 つのアイテムのコレクションの有効なインデックスは 0、1、2、および 3 のみです。コレクションの長さである 4 は有効なインデックスではありません。



Source link

コメント

タイトルとURLをコピーしました