Given a list of users with their opt-in statuses and sequential change log of opt-in status updates that is applied to user list, I am trying to write a function to get a list of all user_ids (sorted by id) that had their opt-in status changed after processing of the change log
Sample Input:
JavaScript
x
38
38
1
current_user_list: [
2
User({
3
id: 1,
4
opted_in: false
5
}),
6
User({
7
id: 19,
8
opted_in: true
9
}),
10
User({
11
id: 4,
12
opted_in: true
13
}),
14
User({
15
id: 54,
16
opted_in: false
17
})
18
]
19
20
opt_in_change_log: [
21
OptInChange({
22
user_id: 19,
23
action: 'opt_out'
24
}),
25
OptInChange({
26
user_id: 1,
27
action: 'opt_in'
28
}),
29
OptInChange({
30
user_id: 71,
31
action: 'opt_in'
32
}),
33
OptInChange({
34
user_id: 19,
35
action: 'opt_in'
36
})
37
]
38
Sample Output
JavaScript
1
2
1
[ 1, 71 ]
2
My function takes two parameters, but I am not entirely sure how to extract user_id who had their opt-in changed
JavaScript
1
3
1
def find_users_with_opt_change(current_user_list, opt_in_change_log):
2
3
EDIT: users not stored in user list are considered opted_out
Advertisement
Answer
I would do it this way
JavaScript
1
21
21
1
def find_users_with_opt_change(current_user_list, opt_in_change_log):
2
current_values = {}
3
was_changed = []
4
5
for i in current_user_list:
6
current_values[i.id] = i.opted_in
7
8
9
for change in opt_in_change_log:
10
user_id = change.user_id
11
current_value = current_values.get(user_id, False)
12
13
if (current_value and change.action == 'opt_out') or (not(current_value) and change.action == 'opt_in'):
14
current_values[user_id] = not(current_value)
15
if user_id in was_changed:
16
was_changed.remove(user_id)
17
else:
18
was_changed.append(user_id)
19
20
return was_changed
21