gpt4 book ai didi

python - 为什么 Python 使用属于外部包的方法会出现递归错误

转载 作者:行者123 更新时间:2023-12-01 01:19:05 25 4
gpt4 key购买 nike

我正在尝试构建计算给定列表的平均值、中位数和众数的函数。仅对于模式,我使用 from stats import mode (其他一切都是手动的),但在输出结果时,仅使用 mode() 的代码行> 方法给我一个递归错误。

这是我的代码:

import pandas as pd
from statistics import mode

dataFrame = pd.read_csv("https://archive.ics.uci.edu/ml/machine-learning-databases/forest-fires/forestfires.csv")

area = dataFrame['area'].tolist()
rain = dataFrame['rain'].tolist()

months = dataFrame['month'] = dataFrame['month'].map({'jan': 1, 'feb': 2, 'mar': 3, 'apr': 4, 'may': 5, 'jun': 6, 'jul': 7, 'aug': 8, 'sep': 9, 'oct': 10, 'nov': 11, 'dec': 12}).tolist()

def mean(numbers):
meanOfNumbers = (sum(numbers))/(len(numbers))
return meanOfNumbers

def median(numbers):
if(len(numbers) % 2 == 0):
medianOfNumbers = (numbers[int((len(numbers))/2)] + numbers[int((len(numbers))/2-1)])/2
else:
medianOfNumbers = numbers[int((len(numbers)-1)/2)]
return medianOfNumbers

def mode(numbers):
modeOfNumbers = int(mode(numbers))
return modeOfNumbers

print("The mean of the months is: " + str("%.2f" % round(mean(months))))
print("The median of the months is: " + str("%.2f" % round(median(months))))
print("The mode of the months is: " + str(mode(months)))

这是错误:

The mean of the months is: 7.00
The median of the months is: 8.00
---------------------------------------------------------------------------
RecursionError Traceback (most recent call last)
<ipython-input-29-ad10a2f4e71b> in <module>()
33 print("The mean of the months is: " + str("%.2f" % round(mean(months))))
34 print("The median of the months is: " + str("%.2f" % round(median(months))))
---> 35 print("The mode of the months is: " + str(mode(months)))
36
37

<ipython-input-29-ad10a2f4e71b> in mode(numbers)
28
29 def mode(numbers):
---> 30 modeOfNumbers = int(mode(numbers))
31 return modeOfNumbers
32

... last 1 frames repeated, from the frame below ...

<ipython-input-29-ad10a2f4e71b> in mode(numbers)
28
29 def mode(numbers):
---> 30 modeOfNumbers = int(mode(numbers))
31 return modeOfNumbers
32

RecursionError: maximum recursion depth exceeded

最佳答案

在你的mode中,你试图调用statistics.mode,但是当你写mode(numbers)时,它意味着函数您已经定义了名为模式。所以这是一个无限递归。

如果您必须有一个名为 mode 的函数,并且还需要使用 statistics.mode,则可以使用其限定名称来区分您所指的函数。

import statistics

...

def mode(numbers):
return int(statistics.mode(numbers))

关于python - 为什么 Python 使用属于外部包的方法会出现递归错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54019010/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com