In: Computer Science
Given a collection of actions and userIds an error occurs when a userId takes a specific action in order for example. Preferably in Javascript. Python or Java is okay too.
A => B => => C gives an errror
B => A => C no error and etc
Write a function that takes in a list of (Actions, UserIds) pairs and returns the user Id that ecounters the error
Sample Input:
action_user_1 = [
["A", "1"],
["B", "1"],
["B", "2"],
["C", "1"],
["C", "2"],
["C", "3"],
["A", "2],
["A", "3"],
["A", "2"],
["B", "2],
["C", "2"],
]
Expected output 1,2
action_user_2 = [
["A", "1"],
["A", "1"]
["A", "1"]
["B", "1"],
["B", "2"],
["C", "2"],
["C", "2"],
["C", "3"],
["A", "2],
["A", "3"],
["A", "2"],
["B", "2],
["C", "2"],
]
Expected output 2
def ErrorUsers(action_user):
'''
Returns the error userids
'''
uniq_user = set() #unique userids
error = []
for lst in action_user: #for each userid
uniq_user.add(lst[1]) #add into a set to get unique values
for user in uniq_user: #for each user
u=[]
for lst in action_user: #for each action list
if user == lst[1]: #if user == action user
u.append(lst[0]) #append the action
new=''.join(u) #make a string by joining the characters within a action list u
if 'ABC' in new: #if ABC in order present then error user append
error.append(user)
elif 'BC' in new: #if BC in order present then error user append
error.append(user)
return error #return the error user list
if __name__ == "__main__":
action_user_1 = [
["A", "1"],
["B", "1"],
["B", "2"],
["C", "1"],
["C", "2"],
["C", "3"],
["A", "2"],
["A", "3"],
["A", "2"],
["B", "2"],
["C", "2"],
]
print(action_user_1)
print("Error users: ",','.join(ErrorUsers(action_user_1)))
action_user_2 = [
["A", "1"],
["A", "1"],
["A", "1"],
["B", "1"],
["B", "2"],
["C", "2"],
["C", "2"],
["C", "3"],
["A", "2"],
["A", "3"],
["A", "2"],
["B", "2"],
["C", "2"],
]
print(action_user_2)
print("Error users: ",','.join(ErrorUsers(action_user_2)))
Output:
Though I write comment with each line if you have any doubt you can ask in the comment. Thanks.