In: Computer Science
IN PYTHON
Given a string with duplicate characters in it. Write a program to generate a list that only contains the duplicate characters. In other words, your new list should contain the characters which appear more than once.
Suggested Approach
Sample Output 1
List of duplicate chars: ['n', 'a']Sample Input 2
pneumonoultramicroscopicsilicovolcanoconiosisSample Output 2
List of duplicate chars: ['p', 'n', 'u', 'm', 'o', 'l', 'r', 'a', 'i', 'c', 's']Sample Input 3
pulchritudinousSample Output 3
List of duplicate chars: ['u', 'i']Sample Input 4
ordenSample Output 4
List of duplicate chars: []
Here is the Python code to the given question.
Four sample outputs are added at the end.
Code:
inputString=input("Enter the string:") #stores input string entered by the user
duplicateList=[] #creates empty list to store duplicate chars
for i in range(len(inputString)): #runs loop from i=0 to last element of string
for j in range(i+1,len(inputString)): #runs loop from j=i to last element of string
if inputString[i]==inputString[j] and inputString[i] not in duplicateList: #checks if two characters are equal and duplicate char is not already present in duplicateList
duplicateList.append(inputString[i]) #append the present char to duplicateList
break #exit from inner loop
print("List of duplicate chars: ",duplicateList) #prints the duplicate list
Sample Output-1:
Sample Output-2:
Sample Output-3:
Sample Output-4: