Sean Sean - 1 year ago 86
Python Question

Create List of 100 Random Integers, Return Max Value

Write a Python function that will take a the list of 100 random integers between 0 and 1000 and return the maximum value. (Note: there is a builtin function named max but pretend you cannot use it.)

Here's what I tried:

import random

list = []
for i in range(100):

def max(list):
#sort list from least to greatest
answer = list.sort()
#get last item in list (max value)

return max

print (max(list))

As you can see, what I'm confused about is how to correctly use the sort and pop methods to return the max value within the max function. I'm currently getting:

ParseError: bad input on line 12

Which is this line:


Not sure how to correct this. Thanks.

Answer Source

my_list.sort() sorts the list itself. If you want to store your sorted list in answer, you should use:

answer = sorted(my_list)

You can also use a list comprehension to generate your first list as follows:

>>> random
>>> my_list = [random.randint(0, 1000) for i in range(100)]
>>> answer = sorted(my_list)
>>> answer.pop()
996  # This should be different each time

Now, your function can be:

def max(my_list):
    # sort list from least to greatest
    answer = sorted(my_list)
    # get last item in list (max value)
    max = answer.pop()

    return max

If you still want to use the same list, you can do:

max = my_list.pop()

Note that: I prefer to call the list my_list because list is a python keyword.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download