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:
current_user_list: [ User({ id: 1, opted_in: false }), User({ id: 19, opted_in: true }), User({ id: 4, opted_in: true }), User({ id: 54, opted_in: false }) ] opt_in_change_log: [ OptInChange({ user_id: 19, action: 'opt_out' }), OptInChange({ user_id: 1, action: 'opt_in' }), OptInChange({ user_id: 71, action: 'opt_in' }), OptInChange({ user_id: 19, action: 'opt_in' }) ]
Sample Output
[ 1, 71 ]
My function takes two parameters, but I am not entirely sure how to extract user_id who had their opt-in changed
def find_users_with_opt_change(current_user_list, opt_in_change_log):
EDIT: users not stored in user list are considered opted_out
Advertisement
Answer
I would do it this way
def find_users_with_opt_change(current_user_list, opt_in_change_log): current_values = {} was_changed = [] for i in current_user_list: current_values[i.id] = i.opted_in for change in opt_in_change_log: user_id = change.user_id current_value = current_values.get(user_id, False) if (current_value and change.action == 'opt_out') or (not(current_value) and change.action == 'opt_in'): current_values[user_id] = not(current_value) if user_id in was_changed: was_changed.remove(user_id) else: was_changed.append(user_id) return was_changed