HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Prompt user for some numbers, then print the max and min

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
theusernumbersminprintmaxsomeforthenand

Problem

The function of this program is repeatedly prompting a user for integer numbers until the user enters 'done'. Once 'done' is entered, print out the largest and smallest of the numbers. Suppose all input is proper, so we do not need to check whether the input value is illegal or not.

largest = None
smallest = None

while True :
    num = raw_input("Enter a number: ")
    if num == "done" :
        break
    try :
        num = int(num)
    except :
        print "Invalid input"
        continue
    if largest is None :
        largest = num
    elif largest < num :
        largest = num
    if smallest is None :
        smallest = num
    elif num < smallest :
        smallest = num

print "Maximum is", largest
print "Minimum is", smallest

Solution

It's a shame python doesn't have a do..while loop, which would have been a better fit for the occasion.

You do plenty of branching. For every valid input, you check if the extreme values so far are still None. If you think about it, this will only be the case the first time a valid value is entered. It's not very plausible to keep on performing that check and it needlessly bloats the code.

To find maximum and minimum efficiently, use max() and min() and initialise your variables with appropriate values, that make the initial case blend in with the rest of the operation. +/-Infinity are good candidates for such values. Everything is bigger than -infinity, which makes it ideal as a starting value for the largest number. Here's what your code would look like with those changes applied:

largest = -float('inf')
smallest = float('inf')

while True :
    num = raw_input("Enter a number: ")
    if num == "done" :
        break
    try :
        num = int(num)
    except :
        print "Invalid input"
        continue

    largest = max(num, largest)
    smallest = min(num, smallest)

print "Maximum is", largest
print "Minimum is", smallest

Code Snippets

largest = -float('inf')
smallest = float('inf')

while True :
    num = raw_input("Enter a number: ")
    if num == "done" :
        break
    try :
        num = int(num)
    except :
        print "Invalid input"
        continue

    largest = max(num, largest)
    smallest = min(num, smallest)

print "Maximum is", largest
print "Minimum is", smallest

Context

StackExchange Code Review Q#143518, answer score: 4

Revisions (0)

No revisions yet.