5 Best Ways to Find Common Characters in Two Strings Using Python

πŸ’‘ Problem Formulation: In this article, we tackle the challenge of writing Python code to identify the common characters between two strings and output them in alphabetical order. For instance, given the strings “bicycle” and “cycle”, the desired output would be “ce”.

Method 1: Using Set Intersection and Sorted Function

This method involves converting both strings into sets and then finding their intersection, which gives us the common elements. The result is then sorted alphabetically using Python’s built-in sorted() function.

Here’s an example:

str1 = "bicycle"
str2 = "cycle"
common_chars = sorted(set(str1) & set(str2))
print(''.join(common_chars))

Output: ce

This snippet first creates sets from the input strings and then computes their intersection, which holds only the common elements. It then sorts the result and joins it into a string for output.

Method 2: Using List Comprehension and Sort Method

List comprehension is used to iterate over one string and collect characters that are also found in the other string. Then, the sort() method is used to order the list alphabetically.

Here’s an example:

str1 = "bicycle"
str2 = "cycle"
common_chars = [char for char in str1 if char in str2]
common_chars.sort()
print(''.join(common_chars))

Output: ce

In this code, we use list comprehension to filter characters and the sort() method to arrange them. The result is then joined into a string for the final output.

Method 3: Using a Traditional For-Loop and Sorting

For those who prefer a traditional approach, iterating through each string character by character using for-loops is the way to go, checking for commonalities. Once found, the results are sorted and displayed.

Here’s an example:

str1 = "bicycle"
str2 = "cycle"
common_chars = []

for char in str1:
    if char in str2 and char not in common_chars:
        common_chars.append(char)

common_chars.sort()
print(''.join(common_chars))

Output: ce

This approach uses a for-loop to manually iterate and check for common characters, adds them to a list while avoiding duplicates, and then sorts and joins them into the final string.

Method 4: Using Collections Counter

Python’s collections.Counter class can be very handy for tallying elements. By using it on both strings and finding their intersection, one can get the count of each common letter and print them in order.

Here’s an example:

from collections import Counter

str1 = "bicycle"
str2 = "cycle"
counter1 = Counter(str1)
counter2 = Counter(str2)
common_chars = sorted((counter1 & counter2).elements())
print(''.join(common_chars))

Output: ce

In this example, the Counter objects tally the character occurrences and the intersection identifies the common character counts. The sorted() function then sorts them alphabetically for output.

Bonus One-Liner Method 5: Using Set, Intersection and Sorted in a Single Statement

Combining all the techniques from previous methods, we can encapsulate the logic in a neat one-liner that’s both efficient and concise.

Here’s an example:

print(''.join(sorted(set("bicycle") & set("cycle"))))

Output: ce

This one-liner performs the set conversion, intersection, sorting, and joining operations all chained together for a swift and elegant solution to the problem.

Summary/Discussion

  • Method 1: Set Intersection and Sorted Function. Strengths are simplicity and efficiency. The weakness is a lack of compatibility with non-hashable elements (like lists).
  • Method 2: List Comprehension and Sort Method. It’s a bit more verbose than using sets and the intersection can be less efficient. Strength lies in readability.
  • Method 3: Traditional For-Loop and Sorting. This method is the most straightforward and educative for beginners. However, it can be inefficient for long strings.
  • Method 4: Using Collections Counter. Offers detailed control over the frequency of characters and is efficient. However, it may be less intuitive for beginners.
  • Method 5: One-Liner. The strength of this method is its compactness and elegance. The downside might be that it can be less readable for those unfamiliar with chaining methods.