Home > Back-end >  Find user with lowest latency from log file
Find user with lowest latency from log file

Time:05-15

I have an input file which has following log entires.

200,John,/home,60ms
200,Sarah,/log,13ms
500,Jack,/home,40ms

Output:

sarah

CodePudding user response:

I assume, your datas are in a txt file

file = "path/to/user_data.txt"

def find_lowest(file):
    with open(file, 'r') as f:
        # Create list that contains every latency 
        # Because you cannot know the lowest or the max latency before check them all
        latencies = [] 
        names = []
        # Make a loop through users'data
        for user_data in f.readlines():
            data = user_data.strip('\n').split(",")  # Convert a row (string) into list
            latencies.append(int(data[3][:-2]))  # [:-2] to remove "ms"
            names.append(data[1])

    return names[latencies.index(min(latencies))]  # Return the first occurence

It gives one user's name with the lowest latency, if two are equal it return only the first user with this latency

If you want a list with all users with the lowest frequency, just replace the last line with :

return [names[i] for i, lat in enumerate(latencies) if lat == min(latencies)]
  • Related