Python Program that Displays Letters that are not Common in Two Strings

This Python program finds and displays letters that are not common in two strings.

Problem Statement

You are tasked with writing a Python program to determine and display the letters that are not common between two input strings.

Python Program that Displays Letters that are not Common in Two Strings

def uncommon_letters(str1, str2):
    set1 = set(str1)
    set2 = set(str2)
    
    uncommon = set1.symmetric_difference(set2)
    
    return uncommon

string1 = input("Enter the first string: ")
string2 = input("Enter the second string: ")

result = uncommon_letters(string1, string2)

print("Letters that are not common:", ', '.join(result))

How it Works

  1. Function Definition:pythonCopy codedef uncommon_letters(str1, str2): We define a function called uncommon_letters that takes two string arguments str1 and str2.
  2. Creating Sets:pythonCopy codeset1 = set(str1) set2 = set(str2) We convert each input string into sets using the set() function. A set is an unordered collection of unique elements. This helps us to efficiently find the unique letters in each string.
  3. Finding Uncommon Letters:pythonCopy codeuncommon = set1.symmetric_difference(set2) The symmetric_difference() method of sets returns a new set containing all elements that are in either of the sets, but not in their intersection. In other words, it gives us the unique elements from both sets.
  4. Returning Uncommon Letters:pythonCopy codereturn uncommon The uncommon_letters function returns the set of letters that are not common between the two input strings.
  5. Taking User Input:pythonCopy codestring1 = input("Enter the first string: ") string2 = input("Enter the second string: ") The program prompts the user to enter two strings.
  6. Calling the Function and Getting Results:pythonCopy coderesult = uncommon_letters(string1, string2) The uncommon_letters function is called with the input strings, and the result is stored in the result variable.
  7. Displaying Output:pythonCopy codeprint("Letters that are not common:", ', '.join(result)) The program prints the unique letters using the join() function to create a comma-separated string from the set.

For example, if you enter "hello" and "world" as input, the program converts them into sets {'h', 'e', 'l', 'o'} and {'w', 'o', 'r', 'l', 'd'} respectively. The symmetric difference between these sets gives {'h', 'e', 'd', 'r', 'w'}, which are the letters not common between the two strings. The program then prints this set of letters as the output.

Input/ Output