Code To Output The First Repeated Character In Given String?
Solution 1:
You can do this in an easier way:
letters = 'acbdc'
found_dict = {}
for i in letters:
if i in found_dict:
print(i)
breakelse:
found_dict[i]= 1
Output:
c
Solution 2:
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)
breakelse:
seen.add(letter)
Solution 3:
Here is a solution that would stop iteration as soon as it finds a dup
>>>from itertools import dropwhile>>>s=set(); next(dropwhile(lambda c: not (c in s or s.add(c)), letters))
'c'
Solution 4:
You should use range(0, len(letters))
instead of range(0, len(letters) - 1)
because range
already stops counting at one less than the designated stop value. Subtracting 1 from the stop value simply makes you skip the last character of letters
in this case.
Please read the documentation of range: https://docs.python.org/3/library/stdtypes.html#range
Solution 5:
There were a few issues with your code...
1.Remove -1
from len(letters)
2.Move back one indent and do b = b + 1
even if you don't go into the if statement
3.Indent and do a = a + 1
in the first for loop.
See below of how to fix your code...
letters='acbdc'for a inrange(0, len(letters)):# print(letters[a])for b inrange(0, len(letters)):# print(letters[b])if(letters[a]==letters[b]) and (a != b):
print(b)
b = b +1
a = a +1
Post a Comment for "Code To Output The First Repeated Character In Given String?"