简体   繁体   中英

How to get largest and smallest number in a sorted list?

def list_stats(values, num_int, low_range, high_range):  # function to fix
    values = generate_integer_list(num_int, low_range, high_range)
    new_val = values.sort()
    low_val = new_val[0]
    high_val = new_val[num_int - 1]
    total = 0
    i = 0
    for num in range(num_int-1):
        i = i + 1
        num = values[i]
        total = total + num
    avg = total/num_int
    return total, low_val, high_val, avg


def generate_integer_list(num_int, low_range, high_range): # generates random #'s
    values = []
    for count in range(num_int):
        number = random.randint(low_range, high_range)
        values.append(number)
    return values

I have to find the largest and smallest number in a generated list, get the total of the all numbers in the list and the average. My numbers are generated by generate_integer_list.

I've used the sort function to sort the generated list, and then grab the first and last number in that list for the smallest and largest. However, the values being returned are not in anyway correct. I've tried giving the sorted list a new name, but that does not work.

The only way i can return proper values is if i print the sorted list, but I am not allowed to do that with regards to the question. How can I fix this?

Your code to calculate the total skips over the first value; just loop over the list of numbers directly , no need to create a range here:

total = 0
for num in values:
    total = total + num

You can do this without resorting to sorting; you already have to loop over all the numbers:

def list_stats(values, num_int, low_range, high_range):
    values = generate_integer_list(num_int, low_range, high_range)
    total = 0
    low_val = high_val = values[0]  # something to start with
    for num in values:
        total += num
        if num < low_val:
            low_val = num
        if num > high_val:
            high_val = num
    avg = total / num_int
    return total, low_val, high_val, avg

I replaced total = total + num with total += num as it comes down to the same thing for numbers.

I also started low_val and high_val off with the first value in the list of values; the loop will then find any lower or higher values as it goes along.

There are a couple BIFs that you could use to simplify this if that is the direction you choose.

sum(numlist) # the sum of your random list
sum(numlist) / len(numlist) # average your list
sorted(numlist, key=int)[0] # lowest element
numlist[len(numlist) - 1] # list is already sorted this gives you the max

Just quick snippets; I didn't rewrite your code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM