Finding minimum, maximum value of a list in Python

Question:

I’m writing a program that, via a while loop, takes user-entered data and adds each value to a list (they’re temperatures) until the user enters ‘q’ (quit). I need to find the minimum and maximum value of the list. Here is my code so far:

temps = []
daily = 1

daily = float(daily)
while daily != "q":
    daily = (raw_input("Today's Temperature: "))
    if str.isdigit(daily) and daily>0:
        temps.append(daily)
    elif daily<0:
        print "Positive temperatures only please."
else: 
    print "Calculating statistics..."

temps = sorted(temps)
print map(float, temps)

maximum = (max(temps))
print "Maximum:",maximum

When I run this and enter values (90, 80, 70, 60, 50, q) it works fine and gives me 90 as the maximum and 50 as the minimum.

However, when I run this and enter values (30, 28, 1, 9, 26, 14, q) it returns 9 as the maximum and 1 as the minimum.

Basically, it treats 9.0 as greater than any number that starts with 8 or less. (i.e. 88, 56, 30, etc.)

How do I fix that?

Asked By: Evan

||

Answers:

You are never converting daily to a float inside your loop, thus all those values in the lists are strings. And as a string, "9" is larger than "30". Similarly, your comparison daily>0 does not work as expected, as you are comparing strings with numbers; this condition will always be true — except in Python 3, where it will rightfully raise an exception.

I suggest you try something like this:

while True:
    daily = raw_input("Today's Temperature: ")
    if daily == "q":
        break
    elif daily.isdigit() and float(daily) > 0:
        temps.append(float(daily))
    else:
        print "Positive numeric temperatures only please."
Answered By: tobias_k

I made some changes in your code so you compare float numbers instead of strings. I also used sort instead of mapping (but it was just to show you another way).

temps = []

while True:
    daily = raw_input("Today's Temperature: ")
    if daily == 'q':
        break
    elif daily.isdigit():
        daily = float(daily)  # after this you can do whatever you want with daily as a number
        if daily > 0:
            temps.append(daily)
        elif daily == 0:
            print "Temperature 0 is not allowed."
    else:
        print "Only possitive numbers for temperature please."


temps.sort()
print temps[0]  # returning the minimum value
print temps[-1]  # returning the maximum value

You can also use heaps (if you want to assure a logarithmic running time):

import heapq

heapq.heapify(temps)
print heapq.nsmallest(1, temps)
print heapq.nlargest(1, temps)
Answered By: rxmxn
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.