I have an array:
arr = ['ab', 'ac']
I want to check which letters are repeated for all items in arr. For the above, 'a' is in both. I would then want to print '1'.
Another example would be:
arr = ['abc', 'dca', 'ac']
'a' and 'c' are common to all, so I would print 2.
Any idea how to do this?
You can make a set of the letters of each string, and determine the intersection of all sets:
arr = ['abc', 'dca', 'ac']
common = set.intersection(*(set(string) for string in arr))
print(common)
# {'a', 'c'}
print(len(common))
# 2
set.intersection
accepts any number of arguments, we use the *
to unpack the generator expression yielding the sets.
You can convert your entries into sets, then find their intersection:
arr = ['abc', 'dca', 'ac']
set_list = [set(a) for a in arr]
intersection = set.intersection(*set_list)
print(intersection)
print(len(intersection))
Output:
{'c', 'a'}
2
References:
here i converted the first element of list to to set for using thee intersection and it worked pretty good
list_of_sets=['acb', 'ac']
print(len(set(list_of_sets[0]).intersection(*list_of_sets[1:])))
Using set
and reduce
could help out here:
from functools import reduce
print(len(reduce(lambda x,y: set.intersection(set(x),set(y)),arr)))
ouputs
2
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.