Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Finding average of the numbers in each line Python

I have a program which grabs the drivers laptimes and writes them to a txt file.
output.txt looks like this:

 00:01:26.102
 00:01:15.618
 00:01:15.096
 00:01:14.792
 00:01:14.532
 00:01:25.083
 00:01:25.497
 00:01:17.809
 00:01:19.364
 00:01:18.935
 00:01:18.076
 00:01:18.111
 00:01:22.086
 00:01:20.500
 00:01:18.167
 00:01:18.268
 00:01:18.373
 00:01:17.950
 00:01:17.944

I want to sum all the lap times and divide it by lap count(basically find the average of them). But i cant manage to sum them correctly. How can i do it?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use timedelta

import datetime as dt

def avg_time(lst:list):
    n=len(lst)
    print(n)
    res=[]
    for i in lst:
        hour,minute,second =i.split(":")
        second,milli=second.split(".")
        res.append(dt.timedelta(hours=int(hour),minutes=int(minute),seconds=int(second),milliseconds=int(milli)))
    return sum(res,res[0])/n


t = ["00:01:26.102","00:01:15.618","00:01:15.096","00:01:14.792","00:01:14.532","00:01:25.083","00:01:25.497","00:01:17.809","00:01:19.364",
"00:01:18.935","00:01:18.076","00:01:18.111","00:01:22.086","00:01:20.500","00:01:18.167","00:01:18.268","00:01:18.373","00:01:17.950","00:01:17.944",]

a = avg_time(t)
print(a)

Output:

0:01:23.600263

PS. you can not format timedelta like other datetime object. So you can use some normal Maths to get it as follows:

total_second=a.total_seconds()
hour_s,second_s=divmod(total_second,3600)
minute_s,second_s=divmod(second_s,60)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading