dimanche 21 février 2016

Handling the various permutations of the diff between two lists

Given two lists todays_ids and baseline_ids, I will use the following to compile differences between them:

    # Status                     added_ids             removed_ids
    # No IDs removed, none added []                    []
    # IDs removed, none added    []                    [id1, id2, ..]
    # IDs added, IDs removed     [id1, id2, ..]        [id1, id2, ..]
    # IDs added, none removed    [id1, id2, ..]        []

    added_ids = [_id for id in todays_ids if _id not in baseline_ids]
    removed_ids = [_id for id in baseline_ids if _id not in todays_ids]

I then need to take different actions, depending on which of the the four possible outcomes is the case for any given execution. For simplicity, let's imagine that I need to just print all the relevant ids in each case.

if len(added_ids) == 0 and len(removed_ids) > 0
   print 'No new ids'
   print 'The following ids were removed_ids:'
   for _id in removed_ids:
       print _id 

elif len(added_ids) > 0 and len(removed_ids) > 0
   print 'The following ids were added:'
   for _id in added_ids:
       print _id 
   print 'The following ids were removed:'
   for _id in removed_ids:
       print _id 

elif len(added_ids) > 0 and len(removed_ids) == 0
   print 'The following ids were added:'
   for _id in added_ids:
       print _id 
   print 'No ids removed'

else:
    print 'No ids added or removed'

Clearly there is some duplicated effort here, and unnecessarily so. How can it be improved?

Aucun commentaire:

Enregistrer un commentaire