Concatenated string with uncommon characters in Python
The goal is to combine two strings and identify the characters that appear in one string but not the other. These uncommon characters are then joined together in a specific order. In this article, we'll explore various methods to solve this problem using Python.
Using set symmetric difference
We can use the symmetric difference operation of the set to pull out all the uncommon characters from both the string and make a string.
s1 = 'aacdb'
s2 = 'gafd'
# Find and join uncommon characters
print(''.join(set(s1) ^ set(s2)))
Output
fbgc
Explanation:
- set(s1) and set(2): This converts the string s1 and s2 into a set of unique characters. This removes any duplicates.
- ^ (Symmetric Difference): This operator performs a symmetric difference between two sets. It returns all elements that are in either set(s1) or set(s2), but not in both.
- ''.join(): ThisJoins the resulting set of characters back into a string without spaces.
Let's understand different methods to concatenated string with uncommon characters .
Using collections.Counter
collections.Counter count the occurrences of each character in the combined strings, then filters out characters that appear more than once.
from collections import Counter
s1 = 'aacdb'
s2 = 'gafd'
f = Counter(s1 + s2)
# Filter and collect characters that appear only once
res = [ch for ch in s1 + s2 if f[ch] == 1]
print(''.join(res))
Output
cbgf
Explanation:
- Counter(str1 + str2): This counts all characters in the combined string str1 + str2.
- List comprehension: This Filters out characters that appear more than once.
- ''.join(result): This combines the filtered characters into a string.
Using Dictionary
This method uses a dictionary to manually count the frequency of characters in the combined strings, then filters out those that appear only once.
s1 = 'aacdb'
s2 = 'gafd'
# Initialize an empty dictionary
f = {}
for ch in s1 + s2:
f[ch] = f.get(ch, 0) + 1
# Filter characters that appear only once
res = [ch for ch in s1 + s2 if f[ch] == 1]
print(''.join(res))
Output
cbgf
Explanation:
- Frequency dictionary: It is used to count the occurrences of each character in the combined strings s1 + s2.
f[ch] == 1
): This filters out characters that appear only once.- ''.join(res): This joins the filtered characters into a final string.
Using two pass filtering
This method identifies common characters between two strings and then filters them out in separate passes. It is simple but less efficient due to the extra overhead of processing the strings twice.
s1 = 'aacdb'
s2 = 'gafd'
c = set(s1) & set(s2)
# Filter out common characters in two passes
res = ''.join([ch for ch in s1 if ch not in c] + [ch for ch in s2 if ch not in c])
print(res)
Output
cbgf
Explanation:
- set(s1) & set(s2): This finds the intersection of s1 and s2, i.e., the common characters.
- Two-pass filtering: This filters the characters in both strings by checking if they are not in the common set.