Concatenated string with uncommon characters in Python

Concatenated string with uncommon characters in Python

In this tutorial, we will see how to generate a concatenated string with uncommon characters from two given strings. An uncommon character is one that appears only in one of the two strings (and not in both).

Tutorial: Concatenated String with Uncommon Characters in Python

1. Introduction:

We have two strings, say A and B. Our goal is to create a string that contains characters that are not common in both A and B.

For instance, if:

  • A="aacdb"
  • B="gafd"

The output should be: "cbg"

2. Steps to Approach:

  1. Traverse through string A, and for each character:
    • Check if it's not present in string B.
    • If not, add to the result.
  2. Traverse through string B, and for each character:
    • Check if it's not present in string A.
    • If not, add to the result.

3. Code:

def uncommon_concat(str1, str2): # Initialize an empty result string result = "" # Traverse through the first string for char in str1: if char not in str2: result += char # Traverse through the second string for char in str2: if char not in str1: result += char return result # Test str1 = "aacdb" str2 = "gafd" print(uncommon_concat(str1, str2)) # Expected output: "cbg" 

4. Optimization:

The solution provided above involves nested loops (due to the in keyword) and therefore is not optimal for very large strings. This results in a complexity of O(n��m), where n and m are the lengths of str1 and str2 respectively.

For optimization, one can use Python's set data type, which has an average-case time complexity of O(1) for the in operation.

def uncommon_concat_optimized(str1, str2): set1 = set(str1) set2 = set(str2) # Characters that are only in str1 or only in str2 uncommon_chars = set1.symmetric_difference(set2) return ''.join(uncommon_chars) # Test str1 = "aacdb" str2 = "gafd" print(uncommon_concat_optimized(str1, str2)) # Output may vary in order but should have "cbg" 

Conclusion:

This tutorial provided methods to generate a concatenated string with uncommon characters from two given strings. Choose the method that best fits your requirements, and if performance is a concern, consider the optimized approach using sets.


More Tags

mode curly-braces purge jboss docker-swarm keycloak save-as rtsp line-intersection beamer

More Programming Guides

Other Guides

More Programming Examples