如何在python中创建一个只有一个值的直方图

2024-10-05 11:02:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我编写了一个函数aveMean(die,numRolls,numTrials),它需要以下内容:

Blockquote

  • 死,死
  • numRolls,numTrials是正整数
  • 计算一个数的最长运行数超过numRolls rolls数的预期平均值。在
  • 调用makeHistogram来生成所有测试的最长跑步记录的柱状图。柱状图中应该有10个箱子
  • 为x和y轴选择适当的标签。在
  • 返回计算的平均值

Blockquote

一切正常,除了:

  1. 这个单子只有一项

enter image description here

  1. 列表中的项目是相等的

enter image description here

  1. 或者只允许一次掷骰子

enter image description here

这就是它的样子

enter image description here

见第三集。左侧总是有一个小的额外的酒吧(几乎看不见)。我怎样才能摆脱它?我读到一些关于这是由于Python3,但我没有找到解决方案。在

谢谢!在

p.S.I编辑了如何调用直方图的代码以及使用调用创建直方图的函数:

def getMeanAndStd(X):
    mean = sum(X)/float(len(X))
    tot = 0.0
    for x in X:
        tot += (x - mean)**2
    std = (tot/len(X))**0.5
    return mean, std

class Die(object):
    def __init__(self, valList):
        """ valList is not empty """
        self.possibleVals = valList[:]
    def roll(self):
        return random.choice(self.possibleVals)

def makeHistogram(values, numBins, xLabel, yLabel, title=None):
    pylab.hist(values, numBins)
    pylab.xlabel(xLabel)
    pylab.ylabel(yLabel)
    if(title != None): pylab.title(title)
    pylab.show()

def aveMean(die, numRolls, numTrials):
    tries = die
    testList, res = [], []
    for i in range(numTrials):
        count, tempCount, testList = 1, 1, []
        for i in range(numRolls):
            testList.append(tries.roll())
        for i in range(1, numRolls):
            if testList[i-1] == testList[i]:
                count +=1
            else:
                if count > tempCount:
                    tempCount = count
                    count = 1
                else:
                    count = 1
        res.append(tempCount)
    mean, std = getMeanAndStd(res)
    makeHistogram(res, 10, 'Quantity of Consecutive Numbers', 'Consecutive Number per Run')
    return round(mean, 3)

我得到的错误消息是:Unsuccessfully called makeHistogram


Tags: inselffortitledefcountresmean
1条回答
网友
1楼 · 发布于 2024-10-05 11:02:02

def getAverage(die, numRolls, numTrials): """ - die, a Die - numRolls, numTrials, are positive ints - Calculates the expected mean value of the longest run of a number over numTrials runs of numRolls rolls - Calls makeHistogram to produce a histogram of the longest runs for all the trials. There should be 10 bins in the histogram - Choose appropriate labels for the x and y axes. - Returns the mean calculated """ tries = die testList, res = [], [] for i in range(numTrials): count, tempCount, testList = 1, 1, [] for i in range(numRolls): testList.append(tries.roll()) for i in range(1, numRolls): if testList[i-1] == testList[i]: count +=1 else: count = 1 if count > tempCount: tempCount = count if count > tempCount: tempCount = count res.append(tempCount) mean, std = getMeanAndStd(res) makeHistogram(res, 10, 'Quantity of Consecutive Numbers', 'Consecutive Number per Run') return round(mean, 3)

相关问题 更多 >

    热门问题