New to coding and would like help with dictionary/lists and shortening code!

Hi everyone,

I am very new to coding and am self teaching python with the help of Codecademy. I am trying to create a database of my swimming times (ideally in min:sec) in seconds for set distances and would like to be able to run the code to give me the average time per 100m, average time per length (25m) for each individual time but also all times together. I currently have code for 100m and 25m for combined times for each distance but not individually. I have created this database using a dictionary format given I had just completed the ‘Student becomes teacher’ lesson of python 2 and so had some template code to create my defs.

Could anyone help me out? I have written some comments in my code as specific questions I’d like to know a bit more but essentially:
Is a dictionary the best way/most efficient way to record and compute this?
Can the code be streamlined and if so how (so I can progress my learning)
Is the code going to be significantly different if a list is the better way to present the data?
How can I convert the times to mins:secs as seconds is a difficult metric to understand beyond 60

Thanks so much! Happy to clarify and add further info if needed

CJ


distance = {
“250m”: [461.0, 420.0],
“400m”: [742.0, 680.0],
“750m”: [1423.0, 1350.0],
“1km”: [1912.0, 1827.0]
} #Is a dictionary the best way to present this data or is a list better?

def average_time(time):
total = sum(time)
total = float(total)
return total/len(time)

time = [distance]
print(average_time(distance[“250m”]))
print(average_time(distance[“400m”]))
print(average_time(distance[“750m”]))
print(average_time(distance[“1km”]))

def average_per_100m(time):
try_tri = average_time(distance[“250m”])
super_sprint = average_time(distance[“400m”])
sprint = average_time(distance[“750m”])
kilo = average_time(distance[“1km”])
return try_tri/2.5,
super_sprint/4,
sprint/7.5,
kilo/10 #How can I split these to individual lines?

print(average_per_100m(distance[“250m”])) #How do I call this individually i.e. if I only wanted to call average for 750m?
#Am I able to call an individual entry to run the above calcs rather than all of the entries? Or is this the difficulty with a dictionary?

def average_per_length(time):
try_tri = average_time(distance[“250m”])
super_sprint = average_time(distance[“400m”])
sprint = average_time(distance[“750m”])
kilo = average_time(distance[“1km”])
return try_tri/10,
super_sprint/16,
sprint/30,
kilo/40
print(average_per_length(distance[“250m”]))

#How can I convert the times in seconds to min:sec format?
#How can I better shorten my code?

Hey Beta5952534769,

Q & A

Is a dictionary the best way to present this data or is a list better?

Yes, for this test case a dictionary is the best choice

How can I split these to individual lines?

You can try this:

def average_per_100m():    
    try_tri = average_time(distance["250m"])
    super_sprint = average_time(distance["400m"])
    sprint = average_time(distance["750m"])
    kilo = average_time(distance["1km"])
    result = (try_tri, super_sprint, sprint, kilo)

    for res in result:
        print(res)

Am I able to call an individual entry to run the above calcs rather than all of the entries?

You can try this:


def average_per_100m(time, distance):
    d = {'Tri': 2.5, 'Super': 4, 'Sprint': 7.5, 'Kilo': 10}
    return f'{float(average_time(time)) / float(d.get(distance)):.2f}'


print(average_per_100m(distance['250m'], 'Tri'))  # 02:56
print(average_per_100m(distance['400m'], 'Super'))  # 02:57
print(average_per_100m(distance['750m'], 'Sprint'))  # 03:04
print(average_per_100m(distance['1km'], 'Kilo'))  # 03:06

I added an extra parameter (distance) to the function. The function is given a list of times from the dictionary, then you specify the distance type (i.e. Tri, Super, Sprint or Kilo). There is probably a better way to do this but it gets the job done…

How can I convert the times in seconds to min:sec format?

With the datetime module.

import datetime

def average_per_100m(time, distance):
    hashtable = {'Tri': 2.5, 'Super': 4, 'Sprint': 7.5, 'Kilo': 10}
    t = float(average_time(time)) / float(hashtable.get(distance))
    h, m = divmod(t, 60)
    return "%02d:%02d" % (h, m)

print(average_per_100m(distance['250m'], 'Tri'))  # 02:56

How can I better shorten my code?

Complete Code

import datetime

distance = {

    "250m": [461.0, 420.0],
    "400m": [742.0, 680.0],
    "750m": [1423.0, 1350.0],
    "1km": [1912.0, 1827.0]
}


def average_time(time):
    return float(sum(time)) / len(time)


def average_per_100m(time, distance):
    hashtable = {'Tri': 2.5, 'Super': 4, 'Sprint': 7.5, 'Kilo': 10}
    t = float(average_time(time)) / float(hashtable.get(distance))
    h, m = divmod(t, 60)
    return "%02d:%02d" % (h, m)


def average_per_length(time, distance):
    hashtable = {'Tri': 10, 'Super': 16, 'Sprint': 30, 'Kilo': 40}
    time = float(average_time(time)) / float(hashtable.get(distance))
    return f'{time / hashtable.get(distance):.2f}m'


if __name__ == '__main__':
    print(average_per_100m(distance['250m'], 'Tri'))  # 02:56
    print(average_per_100m(distance['400m'], 'Super'))  # 02:57
    print(average_per_100m(distance['750m'], 'Sprint'))  # 03:04
    print(average_per_100m(distance['1km'], 'Kilo'))  # 03:06
    print(average_per_length(distance["250m"], 'Tri'))  # 4.4m

There maybe some glitches in this code, so if you have any further questions or comments please let me know!

Best regards,

1 Like

Thanks for your help.
Final question for now is about how to add a string to the output:
“Average swim time per 100m for %s is: %d”
I have tried to add this but have not succeeded with the only method I currently know how

Your Question: How to add a string to the output?

You should use fstrings to add string to your output:

my_time = average_per_100m(distance['250m'], 'Tri')

print(f'Average swim time per 100m for 250m is: {my_time}')

Glad I could help! If you need further assistance please reach out!