Home > database >  Finding duplicate characters in a string using for loops in Python:
Finding duplicate characters in a string using for loops in Python:

Time:09-25

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! :)

CodePudding user response:

def hasDuplicates(s):
   count = 0  # You may remove this count

CodePudding user response:

your function is just complicated for no reasons, this is a good example you can follow:

from collections import Counter

s = "Hello"
counts = Counter(s)

for character, count in counts.most_common():
    print(character, '-', count)

and then you can continue if count over 1 then do something

CodePudding user response:

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)
  • Related