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 co
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 in range(0, len(letters)):
# print(letters[a])
for b in range(0, len(letters)):
# print(letters[b])
if (letters[a] == letters[b]) and (a != b):
print(b)
b = b + 1
a = a + 1
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
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
def first_repeated_char(str1): for index,c in enumerate(str1): if str1[:index+1].count(c) > 1: return c return "None" print(first_repeated_char("abcdabcd"))
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'
The below code prints the first repeated character in a string. I used the functionality of the list to solve this problem.
def findChar(inputString):
list = []
for c in inputString:
if c in list:
return c
else:
list.append(c)
return 'None'
print (findChar('gotgogle'))
Working fine as well. It gives the result as 'g'.