return is a keyword that works more or less as immediately exit this function (and optionally carry some output with you). You thus need to remove the return statement:
def find_duplicate(): x =input("Enter a word = ") for char in x : counts=x.count(char) print(char,counts)Furthermore you also have to remove the while loop (or update the counter if you want to print multiple times), otherwise you will get stuck in an infinite loop since count is not updated and the test will thus always succeed.
Mind however that in this case a will be printed multiple times (in this case two) if it is found multiple times in the string. You can solve this issue by first constructing a set of the characters in the string and iterate over this set:
def find_duplicate(): x =input("Enter a word = ") for char in set(x): counts=x.count(char) print(char,counts)Finally it is better to make a separation between functions that calculate and functions that do I/O (for instance print). So you better make a function that returns a dictionary with the counts, and one that prints that dictionary. You can generate a dictionary like:
def find_duplicate(x): result = {} for char in set(x): result[char]=x.count(char) return resultAnd a calling function:
def do_find_duplicates(x): x =input("Enter a word = ") for key,val in find_duplicate(x).items(): print(key,val)And now the best part is: you actually do not need to write the find_duplicate function: there is a utility class for that: Counter:
from collections import Counter def do_find_duplicates(x): x =input("Enter a word = ") for key,val in Counter(x).items(): print(key,val)View Discussion
Improve Article
Save Article
View Discussion
Improve Article
Save Article
Given a string, find all the duplicate characters which are similar to each other. Let us look at the example.
Examples:
Input : hello Output : l Input : geeksforgeeeks Output : e g k sWe have discussed a solution in the below post. Print all the duplicates in the input string We can solve this problem quickly using the python Counter() method.
The approach is very simple.
- Create a dictionary using the Counter method having strings as keys and their frequencies as values.
- Declare a temp variable.
- Print all the indexes from the keys which have values greater than 1.
Python
from collections import Counter
def find_dup_char(input):
WC = Counter(input)
for letter, count in WC.items():
if (count > 1):
print(letter)
if __name__ == "__main__":
input = 'geeksforgeeks'
find_dup_char(input)
Approach : Using count() method
Python3
def find_dup_char(input):
x=[]
for i in input:
if i not in x and input.count(i)>1:
x.append(i)
print(" ".join(x))
if __name__ == "__main__":
input = 'geeksforgeeks'
find_dup_char(input)