Skip to content

Instantly share code, notes, and snippets.

@jonhurlock
Last active August 29, 2015 14:13
Show Gist options
  • Save jonhurlock/e48574817c8ee7de3402 to your computer and use it in GitHub Desktop.
Save jonhurlock/e48574817c8ee7de3402 to your computer and use it in GitHub Desktop.
import collections
def first_unique(some_list):
dict_of_items = collections.OrderedDict()
for item in some_list:
if item in dict_of_items:
dict_of_items[item] +=1
else:
dict_of_items[item] = 1
for key in dict_of_items:
if dict_of_items[key] == 1:
return key
return None
# Example input
# print first_unique('aabcc') # we can do this because a string is a list of characters.
# print first_unique([1,2,3,1,2])
# print first_unique(['aa','aa','bc','d'])
"""
Code Breakdown
--------------
line 1: used for importing the ordered dictionary seen in line 4
line 4: We need to use an ordered dictionary to remember what order we added items in,
see http://bit.ly/1ANjFoJ or http://bit.ly/17F80Pc for more information regarding
the OrderedDict collection.
line 6: look at http://bit.ly/1xm0hKD for a interestingn conversation on if item in
dict_of_items vs. item in dict_of_items.keys()
line 7: This increments the count of the number of instances we have seen of this item
line 12: this halts the function once the first unique item is found.
line 13: if no unique value is found return None
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment