Sunday 15 February 2015

coding style - Python Dict vs List for adding unique element only -


To get a foothold of unique elements, is [2] acceptable?

  # [1] If the element is not in the list: list.append (element) # [2] dict [element] = none # value does not matter    

Use as your data structure.

As per the list display, it is not good, checking whether the element is in the list, it takes linear time. This list gradually slows down.

The set also seeks the time to search the language, but you do not need to add a key-value, so it's more beautiful to do:

  S = set () s.add (element)   

to

  s = {} s [element] = none  < / Pre> 

plus you get all the best set operations, such as union, crossroads, etc.

No comments:

Post a Comment