Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the minimum and maximum in python

Tags:

python-2.7

I have to ask the user to put some numbers and then print the size, sum, average, minimum and maximum. I can get the first 3 things but I'm stuck on the minimum and maximum one. The problem I have is I can't use sort() because I need to make the list an integer one, but you can't use an integer list for split()

Here's my code:

    number = raw_input('Enter number:')
    list_of_numbers = number.split()
    tally = 0
    sum = 0
      while number!= '':
        tally = tally + 1
        sum = sum + int(number)
        average = float(sum) / float(tally)
      number = raw_input('Enter number:')
    print "Size:", tally
    print "Sum:", sum
    print "Average:", average

Any hints? Thanks

like image 945
user1008073 Avatar asked Sep 06 '12 02:09

user1008073


2 Answers

Are you allowed to use built-in functions of Python? If yes, it is easier:

number = raw_input('Enter number:')
list_of_numbers = number.split()

numbersInt = map(int, list_of_numbers) # convert string list to integer list

print("Size:",    len(numbersInt))
print("Min:",     min(numbersInt))
print("Max:",     max(numbersInt))
print("Sum:",     sum(numbersInt))
print("Average:", float(sum(numbersInt))/len(numbersInt) if len(numbersInt) > 0 else float('nan'))
# float conversion is only required by Python 2. 

where numbersInt = map(int, list_of_numbers) converts each string number of the list to an integer. Each function has the following meaning:

  • len computes the length of a list
  • min computes the minimum
  • max computes the maximum
  • sum computes the sum of a list

There isn't a mean function in Python standard library. But you can use numpy.mean() instead. Install it with pip install numpy or conda install numpy, then:

import numpy as np
print("Average: ", np.mean(numbersInt))
like image 72
Yamaneko Avatar answered Oct 20 '22 19:10

Yamaneko


I think you can use min() and max() to find those values.

like image 41
Eudis Duran Avatar answered Oct 20 '22 19:10

Eudis Duran