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
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 listmin
computes the minimummax
computes the maximumsum
computes the sum of a listThere 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))
I think you can use min() and max() to find those values.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With