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

时间:2019-01-03 08:54:21

标签: python recursion statistics

我正在尝试构建用于计算给定列表的均值,中位数和众数的函数。仅对于模式,我正在使用from statistics 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

1 个答案:

答案 0 :(得分:2)

mode内部,您正在尝试调用statistics.mode,但是在编写mode(numbers)时,这意味着您定义的函数称为mode。因此,这是无限递归。

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

import statistics

...

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