下面的Python函數用於計算具有大小相等的數據的數據直方圖。我想獲得正確的結果Python-計算一組數據的直方圖
[1, 6, 4, 6]
但是之後我運行代碼,得到它導致
[7, 12, 17, 17]
這是不正確的。任何人都可以知道如何解決它?
# Computes the histogram of a set of data
def histogram(data, num_bins):
# Find what range the data spans, and use it to calculate the bin size.
span = max(data) - min(data)
bin_size = span/num_bins
# Calculate the thresholds for each bin.
thresholds = [0] * num_bins
for i in range(num_bins):
thresholds[i] += bin_size * (i+1)
# Compute the histogram
counts = [0] * num_bins
for datum in data:
# Increment the count of the bin that the datum falls in
for bin_index, threshold in enumerate(thresholds):
if datum <= threshold:
counts[bin_index] += 1
return counts
# Some random data
data = [-3.2, 0, 1, 1.5, 1.6, 1.9, 5, 6, 9, 1, 4, 5, 8, 9, 5, 6.7, 9]
print("Correct result:\t" + str([1, 6, 4, 6]))
print("Your result:\t" + str(histogram(data, num_bins=4)))
你認爲是什麼使得它不正確的? – miradulo
你的代碼是無效的Python。請[編輯]它並修復注意事項。 –
@Tichodroma:感謝您的編輯。 – user21