user6363467
user6363467

Reputation: 124

Find numbers in text file and after that add them but see where the lowest number is as well

How can I find all the numbers in a text file? Then I need to find the average and median of the numbers as well.

def main():
    file = open("grades.txt","r")
    i = file.readlines()
    numbers = file.findall(r'[+-]?\d+(?:\.\d+)?')
    print (numbers)
main()

Text file:

Joe,Sammy,75
Gayle,Ujifusa,95   
Bella,Luna,65
Bob,Jones,0    
Alex,Fink,10    
Nathan,Bono,0    
Bob,Bono,0    
Edith,Bono,0    
Susie,Que,84    
Arnold,George,80    
Linda,Beth,100

Output:

Average of the grades and who has the lowest and highest grade.

Upvotes: 1

Views: 235

Answers (2)

Burgan
Burgan

Reputation: 900

This should work to get a list of the numbers. No need to install anything. This makes assumptions that the file will follow the format you've provided. If you want to find the average look at sum() and len(), and for the median you can use len() again with some logic handling even and odd lengths.

def main():
    file = open("grades.txt","r")
    i = file.readlines()
    numbers = [float(x.split(',')[-1]) for x in i]
    print (numbers)
main()

Upvotes: 2

Abhisek Roy
Abhisek Roy

Reputation: 584

Hope this solves your problem. PS-without numpy as you asked.

import re
from functools import reduce
def median(lst):
    n = len(lst)
    if n < 1:
            return None
    if n % 2 == 1:
            return sorted(lst)[n//2]
    else:
            return sum(sorted(lst)[n//2-1:n//2+1])/2.0

def main():
    file = open("grades.txt","r")
    i = file.readlines()
    num=[]
    for element in i:
        num.extend((re.findall('\d+',element)))
    results = list(map(int, num))
    print(results)
    print (reduce(lambda x, y: x + y, results) / len(results))
    print(median(results))

main()

Upvotes: 0

Related Questions