3
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.

3
  • 3
    You immediately return... Commented Jan 16, 2017 at 18:10
  • 2
    You are looking for collections.Counter Commented Jan 16, 2017 at 18:10
  • 2
    Because when you return the function stops executing... Also, why are you returning the result of a call to print? This will always return None. Commented Jan 16, 2017 at 18:10

6 Answers 6

4

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)
Sign up to request clarification or add additional context in comments.

3 Comments

Of course, this while loop will never terminate in the case where counts > 1.
@juanpa.arrivillaga: good point. Hadn't thaken that into account. Will rewrite my answer.
Counter is only for single characters; is there a way to do the same but make it get duplicates for sequances of 3 charater and more ?
0

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()

Comments

0

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)]

Comments

0
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)

Comments

0

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)

Comments

0
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()

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.