Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Code to output the first repeated character in given string?

Tags:

python

I'm trying to find the first repeated character in my string and output that character using python. When checking my code, I can see I'm not index the last character of my code.

What am I doing wrong?

letters = 'acbdc'
for a in range (0,len(letters)-1):
#print(letters[a])
    for b in range(0, len(letters)-1):
        #print(letters[b])
        if (letters[a]==letters[b]) and (a!=b):
            print(b)
            b=b+1
a=a+1
like image 702
Cathryn Avatar asked Mar 11 '26 16:03

Cathryn


2 Answers

You can do this in an easier way:

letters = 'acbdc'
found_dict = {}
for i in letters:
    if i in found_dict:
        print(i)
        break
    else:
        found_dict[i]= 1

Output: c

like image 184
Taohidul Islam Avatar answered Mar 16 '26 12:03

Taohidul Islam


Here's a solution with sets, it should be slightly faster than using dicts.

letters = 'acbdc'
seen = set()

for letter in letters:
    if letter in seen:
        print(letter)
        break
    else:
        seen.add(letter)
like image 41
bphi Avatar answered Mar 16 '26 11:03

bphi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!