Search code examples
pythonattributeerror

I have Python errors


I am having several python errors in this code and I need help with the code. I'm fairly new to python so I have trouble figuring this out.

Traceback (most recent call last):
  File "/root/sandbox/stats.py", line 74, in <module>
    main()
  File "/root/sandbox/stats.py", line 66, in main
    "Mean of [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]: ", mean(range(1, 11))
  File "/root/sandbox/stats.py", line 25, in mean
    list.range()
AttributeError: 'range' object has no attribute 'range'

this is the error I keep getting.

This is my code

def median(list):
   if len(list) == 0:
       return 0
   list.sort()
   midIndex = len(list) / 2
   if len(list) % 2 == 1:
       return list[midIndex]
   else:
       return (list[midIndex] + list[midIndex - 1]) / 2

def mean(list):
   if len(list) == 0:
       return 0
   list.range()
   total = 0
   for number in list:
       total += number
   return total / len(list)

def mode(list):
   numberDictionary = {}
   for digit in list:
       number = numberDictionary.get(digit, None)
       if number is None:
           numberDictionary[digit] = 1
       else:
           numberDictionary[digit] = number + 1
   maxValue = max(numberDictionary.values())
   modeList = []
   for key in numberDictionary:
       if numberDictionary[key] == maxValue:
           modeList.append(key)
   return modeList

def main():
   print 
   "Mean of [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]: ", mean(range(1, 11))
   print 
   "Mode of [1, 1, 1, 1, 4, 4]:", mode([1, 1, 1, 1, 4, 4])
   print 
   "Median of [1, 2, 3, 4]:", median([1, 2, 3, 4])

main()

I don't know how to actually fix it. I've tried to quick fix and replaced == with the is operator but nothing worked


Solution

  • When you print something make sure you are using opening brackets:

       print("Mean of [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]: ", mean(list(range(1,11))))
       # print("Mode of [1, 1, 1, 1, 4, 4]:", mode([1, 1, 1, 1, 4, 4]))
       print("Median of [1, 2, 3, 4]:", median([1, 2, 3, 4, 5]))
    

    In order to make your median code working you should cast the midIndex to integer type:

    midIndex = int(len(list) / 2)
    

    I rewrote you mean function a bit:

    def mean(list):
        length = len(list)
        if length == 0:
            return 0
        else:
            sum = 0
            for n in list:
                sum += n
        return sum / length
    

    I called this function with a list made with range:

    list(range(1,11))
    

    I am not sure what you want to achieve with your mode function. But perhaps you have had some help now to try this one yourselve.

    Happy coding!