Skip to content

Instantly share code, notes, and snippets.

@riceissa
Created January 10, 2015 20:48
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save riceissa/422a7c89607fcb4a021c to your computer and use it in GitHub Desktop.
Save riceissa/422a7c89607fcb4a021c to your computer and use it in GitHub Desktop.
find the intersection of characters given a list of strings
# Fencepost loop using dictionaries.
def inters_dict(lst):
dct = {ch: True for ch in lst[0]}
for s in lst[1:]:
dct = {ch: True for ch in s if ch in dct}
return dct.keys()
# I suspect Pythonistas would find the use of (ch, True) as key-value
# pairs to be jarring, so here it is using sets---essentially, the
# "True" part is implied by virtue of being in the set.
def inters_set(lst):
st = set(ch for ch in lst[0])
for s in lst[1:]:
st = set(ch for ch in s if ch in st)
return [i for i in st]
# This is the "cool" one-line solution I was thinking of, but couldn't
# come up with on the spot. It essentially creates a set (like in
# inters_set) for each string in the list, then takes the intersection
# of all of them using Python's built-in set.intersection. The star (*)
# unpacks the list of sets so it's like calling set.intersection(s_1,
# s_2, ..., s_n) (but since we don't want to write it like that, we can
# instead write set.intersection(*sets), where sets = [s_1, s_2, ...,
# s_n]).
def inters_set_cool(lst):
return list(set.intersection(*[set(ch for ch in i) for i in lst]))
test_matrix = [
["abbbbcd","abbbbbbb","ca", "bcdae", "efghaab"],
["abc","ab","bcba", "bcdae", "efghaab"],
["abc","ab","bca", "bcdae", "efghab","z"],
]
# This seems to be the "right" way to do "main" in Python.
if __name__ == '__main__':
for lst in test_matrix:
# User can verify all three come out to be the same.
print(inters_dict(lst), inters_set(lst), inters_set_cool(lst))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment