Search code examples
pythonlistrandommax

Does anyone know how to fix a maxed function in Python?


im trying to run a code that finds random numbers between 100 and 199 inclusive but when i run the code it says

heres my code:

import random 
list = []
for i in range(199):
    list.append(random.randint(100,199))
def max(list):
    answer = list.sort()
    list.pop()
    return max  
print (max(list))

here's a screenshot of the output for better clarification when i run it, it says the function maxes out and i dont know how to fix it, please help! Thanks!


Solution

  • Your code as shown will print something like

    <function max at ....>
    

    This doesn't mean that the function has "maxed out". It is showing exactly the thing that you printed.

    In your code, you do print (max(list)). This means that it will print out whatever calling max returns. Looking at the definition of the function, it will always return max.

    So, the print statement is told to print the function named max itself. This is why you get the output <function max> since that is the string representation.

    You probably wanted to define your max function something like this

    def max(list):
        list.sort()
        answer = list.pop()
        return answer
    

    The main difference is returning answer instead of max. Additionally, list.sort() returns None, so you instead need to give answer the value returned from list.pop(), which is the array element. Therefore the function will return an integer that will be printed correctly.

    However, you don't need to do this. Python has a built-in function called max that does this exact thing easier and faster.