user300
user300

Reputation: 465

Finding the Maximum and Minimum value in python using loops

I have an assignment where I let the user input as many scores and then I have to calculate the minimum and maximum value along with how many people got those scores using for-loop. I've calculated the average and the standard deviation:

elif user_option == 3:

    total = 0
    for val in scores_list:
        total = total + val
    average = total/ len(scores_list)
    print (average)
elif user_option == 2:
    total = 0
    for val in scores_list:
        total = total + val
    average = total/ len(scores_list)
    diffsquared = 0
    sum_diffsquared = 0
    for val in scores_list:
        diffsquared= (val - average)**2
        sum_diffsquared= diffsquared + sum_diffsquared
    stdev= sqrt((sum_diffsquared)/len(scores_list))
    print(stdev)

Any ideas how to find the min and max values?

Upvotes: 0

Views: 6341

Answers (2)

Shashank
Shashank

Reputation: 13869

Something like this?

min_val = float("inf")
max_val = -float("inf")
count_min = 0
count_max = 0

for val in scores_list:
    if val < min_val:
        min_val = val
        count_min = 1
    elif val == min_val:
        count_min += 1

    if val > max_val:
        max_val = val
        count_max = 1
    elif val == max_val:
        count_max += 1

print "Minimum score:", min_val
print "Maximum score:", max_val
print "Number of students with minimum score:", count_min
print "Number of students with maximum score:", count_max

EDIT: As @GL770 has noted in the comments, sys.maxint is only available in Python 2.x. In Python 2.x you could have done something like this.:

import sys
min_val = sys.maxint
max_val = -sys.maxint - 1

The float("inf") thing also works in Python 2.x though so this method is not required.

Upvotes: 1

bcollins
bcollins

Reputation: 3459

How about the built-in functions min() and max():

scores_min = min(scores_list)
scores_max = max(scores_list)

also don't forget about numpy:

import numpy
scores_array = numpy.array(scores_list)
scores_mean = numpy.mean(scores_array)
scores_std = numpy.std(scores_array)
scores_min = numpy.min(scores_array)
scores_max = numpy.max(scores_array)

Upvotes: 0

Related Questions