【发布时间】:2016-07-19 13:35:38
【问题描述】:
下面的 Python 函数用于计算具有相同大小的 bin 的数据直方图。我想得到正确的结果
[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)))
【问题讨论】:
-
你认为是什么使它不正确?
-
您的代码不是有效的 Python。请edit它并修复缩进。
-
@Tichodroma:感谢编辑。
-
@Donkey Kong:我想得到正确的结果 [1, 6, 4, 6]