Skip to content
Advertisement

Finding duplicate characters in a string using for loops in Python:

I have a simple question. First of all I want to say that the code I used below works perfectly fine for the purpose of finding duplicate characters in a string (although there might be better solutions to that problem without a doubt). But I struggle to understand why i need to declare the count variable in the first for loop after having declared it in the function already, because if I don’t declare it in the for loop as well, the program will not work properly… :/

def hasDuplicates(s):
   count = 0
   for i in range(0, len(s)):
       count = 0
       for j in range(i+1, len(s)):
           if (s[i] == s[j]):
               count += 1
       if (count == 1):
           print(s[i])

Sorry if it is a silly question, I’m new to programming so thanks for the help! :)

Advertisement

Answer

You’re not declaring the variable inside the loop, you’re assigning to it. This is needed because with out it after the first iteration of the outer loop your counter will retain it’s value. Take the following string: aarron. After the first loop count will retain the value of 1. When searching for the string s this becomes a problem since the final value will be 2. I would suggest an edit to your code, however, since it doesn’t handle strings that have more than one duplicate, such as aaron a. Consider something something a little more compact such as

def hasDuplicates(s):
    for c in s:
        if s.count(c) > 1:
            print(c)
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement