finding duplicates in a string at python 3

Question:

def find_duplicate():
    x =input("Enter a word = ")
    for char in x :
        counts=x.count(char)
        while counts > 1:
            return print(char,counts)

I’ve got small problem in there i want to find all duplicates in string but this program give me only one duplicate ex: aassdd is my input function gave me only a : 2 but it need to be in that form a : 2 s : 2 d : 2 thanks for your answers.

Asked By: Deniz Firat

||

Answers:

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 result

And 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)
Answered By: Willem Van Onsem

This will help you.

 def find_duplicate():
    x = input("Enter a word = ")
    for char in set(x):
        counts = x.count(char)
        while counts > 1:
            print(char, ":", counts, end=' ')
            break
find_duplicate()
Answered By: Shehan V
def find_duplicate():
    x = input("Enter a word = ")
    dup_letters = []
    dup_num = []

    for char in x:
        if char not in dup_letters and x.count(char) > 1:
            dup_letters.append(char)
            dup_num.append(x.count(char))

    return zip(dup_letters, dup_num)

dup = find_duplicate()

for i in dup:
    print(i)
Answered By: Miled Louis Rizk

Just because this is fun, a solution that leverages the built-ins to avoid writing any more custom code than absolutely needed:

from collections import Counter, OrderedDict

# To let you count characters while preserving order of first appearance
class OrderedCounter(Counter, OrderedDict): pass

def find_duplicate(word):
    return [(ch, cnt) for ch, cnt in OrderedCounter(word).items() if cnt > 1]

It’s likely more efficient (it doesn’t recount each character over and over), only reports each character once, and uses arguments and return values instead of input and print, so it’s more versatile (your main method can prompt for input and print output if it chooses).

Usage is simple (and thanks to OrderedCounter, it preserves order of first appearance in the original string too):

>>> find_duplicate('aaacfdedbfrf')
[('a', 3), ('f', 3), ('d', 2)]
Answered By: ShadowRanger

This version should be fast as I am not using any library or more than one cycle, do you have any faster options?

import datetime

start_time = datetime.datetime.now()

some_string = 'Laptop' * 99999

ans_dict = {}

for i in some_string:
  if i in ans_dict:
    ans_dict[i] += 1
  else:
    ans_dict[i] = 1

print(ans_dict)

end_time = datetime.datetime.now()
print(end_time - start_time)

Answered By: JEX
def find_duplicate():
x = input("Enter a word = ")
y = ""
check = ""
for char in x:
    if x.count(char) > 1 and char not in y and char != check:
        y += (char + ":" + str(x.count(char)) + " ")
        check = char
return y.strip()
Answered By: Qithara
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.