Unique characters in each string: Difference between revisions

m
Python alternatives
m (Python alternatives)
Line 766:
print(sorted([ch for ch in set([c for c in ''.join(LIST)]) if all(w.count(ch) == 1 for w in LIST)]))
</lang>{{out}}
<pre>
['1', '2', '3', 'a', 'b', 'c']
</pre>
 
 
Or, avoiding intermediate lists.
 
<lang python>LIST = ["1a3c52debeffd", "2b6178c97a938stf", "3ycxdb1fgxa2yz"]
print(sorted(ch for ch in set("".join(LIST)) if all(w.count(ch) == 1 for w in LIST)))</lang>
 
{{out}}
<pre>
['1', '2', '3', 'a', 'b', 'c']
</pre>
 
 
We can also avoid concatenating all strings in the input list.
 
<lang python>from itertools import chain
 
LIST = ["1a3c52debeffd", "2b6178c97a938stf", "3ycxdb1fgxa2yz"]
 
print(
sorted(
ch
for ch in set(chain.from_iterable(LIST))
if all(w.count(ch) == 1 for w in LIST)
)
)</lang>
 
{{out}}
<pre>
['1', '2', '3', 'a', 'b', 'c']
</pre>
 
 
Or, avoid calling <code>count()</code> for every distinct character in every string in the input list.
 
<lang python>from collections import Counter
 
LIST = ["1a3c52debeffd", "2b6178c97a938stf", "3ycxdb1fgxa2yz"]
 
print(
sorted(
set.intersection(
*(
set(char for char, count in counts.items() if count == 1)
for counts in (Counter(s) for s in LIST)
)
)
)
)</lang>
 
{{out}}
<pre>
['1', '2', '3', 'a', 'b', 'c']
140

edits