jeudi 25 août 2016

Computing the average of non-negative numbers from a text file.

I am trying to read in a text file of integers, make it a list, compute the average of all integers, compute the average of all non-negative integers, print max and min. I was able to compute the average of all integers but am having difficulty getting the average of all non-negative integers and the max and min.

Here is what I have so far:

file = open("numberlist.txt", "r")

sum = 0

list = []
for num in file:
    list.append(num)

for number in list:
    x = int(number)
    sum += x
avg = sum/len(list)
print("The number of integers is ", len(list))
print ("The overall average is ", avg)

poslist = []
for number in file:
    x = int(number)
    if x > 0:
        poslist.append(x)
        sum += number
posavg = sum / len(poslist)
print("The number of non-negative integers is ", len(poslist))
print("The average of the non-negtive integers is ", posavg)

list.sort()
print("The minimum number is ", list[0])
print("The maximum number is ", list[-1])

Aucun commentaire:

Enregistrer un commentaire