In: Computer Science
Please solve the following question by Python3.
Code the function calc_tot_playtime to calculate the total playtime by user and game.
Each element in input is of the format
"user_id, game_id, total_playtime_in_minute".
Input is a list of strings of the above format.
Output should be sorted by user_id, game_id in ascending order.
Example:
Input: ["1,10,20", "1,15,10m", "1,10,10m", "2,10,40m", "2, 20, 10m"]
output: [('1', '10', 30), ('1', '15', 10), ('2', '10', 40), ('2', '20', 10)]
Functions are defined below:
def calc_total_playtime(input_data=None):
"""
your code here
:param: input_data: input list of strings
return output of tuples
index 0 -user_id
index 1 - game_id
index 2- total play time in minutes
"""
Please follow the comments to better understand the code.
Check the screenshot below to better understand the code in indentation form.
=====================================================================
def calc_total_playtime(input_data=None):
#STEP-1 Pre-process the string.
#Convert it into a list of string, using a for loop
temp=[]
for s in input_data:
user_id, game_id, playtime=s.split(',')
playtime=int(playtime[:-1]) #Remove 'm' from the string
temp.append([user_id,game_id,playtime])
#print(temp) #Check the temp data
#This is very important.
#We can sort the list using sorted() function and using a Lambda
Function.
#Here we need to sort the data based on (user_id, game_id)
# i.e, they are 0th and 1st indexes of each of the temp list.
output = sorted(temp, key = lambda x: (x[0], x[1]))
#print(output)
#Now, if two or more users have same (user_id, game_id), then add
their times
final_output=[]
sum=output[0][2]
i=0
while i<len(output)-1:
if output[i][0]==output[i+1][0] and
output[i][1]==output[i+1][1]:
sum+=output[i+1][2]
else:
final_output.append([output[i][0],output[i][1],sum])
sum=output[i+1][2]
i+=1
final_output.append([output[i][0],output[i][1],sum])
#Return the output
return final_output
#Test the function here
#TEST-1
input_data=["1,10,20m", "1,15,10m", "1,10,10m", "2,10,40m",
"2,20,10m","1,15,40m","2,20,50m","3,45,60m"]
print(calc_total_playtime(input_data))
#TEST-2
input_data=["1,10,20", "1,15,10m", "1,10,10m", "2,10,40m",
"2,20,10m"]
print(calc_total_playtime(input_data))
=====================================================================================
==========================
Please feel free to reach out in comments if you have any doubts.
Please give a THUMBS UP...!!!
Happy Learning..!!
===========================