Using Python, Write a function to return all the common characters in two input strings. The return must be a list of characters and only unique characters will be returned. For example, given 'abcdefg' and 'define', the function will return ['d', 'e', 'f'] (note e only appears once). (Hint: Use the in operator.)
Following is what I've done so far. When I enter 'abcdefg' for the first string, and 'define' for the second string, I get ['d','e','f'], which is correct.
But, If I enter 'define' for the first string, and 'abcdefg' for the second string, I get ['d','e','f','e']. (e appears twice)
Could you please tell me what I need to do to get only one 'e'? I can't use Set or python libraries.
common_list = []
def common_characters(str1, str2):
for i in str1:
if i in str2:
common_list.append(i)
return common_list
str1 = str(input("Enter your first string: "))
str2 = str(input("Enter your second string: "))
print(common_characters(str1,str2))
def common_characters(str1, str2): common_list = [] for i in str1: if (i in str2) and not(i in common_list): common_list.append(i) return common_list str1 = str(input("Enter your first string: ")) str2 = str(input("Enter your second string: ")) print(common_characters(str1, str2))
Get Answers For Free
Most questions answered within 1 hours.