2

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
2
  • 1
    remove the -1 from len(letters)-1 - range has an exclusive upper bound Commented Jun 21, 2018 at 19:53
  • 1
    Half of the solutions are doing this wrong, and half are doing it right. Can you clarify what the proper output should be for the string abba? Commented Jun 21, 2018 at 20:17

11 Answers 11

4

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

Sign up to request clarification or add additional context in comments.

4 Comments

You would want a break or return after Print, because they want only the FIRST occurance. Therefore you need to exit your loop.
Thank you. I have written the code for all repeated letters. I am updating it soon.
FWIW, you don't need the call .keys(). x in dict already checks if the key is in the dict. Plus, it is slow in Python 2 :)
You've noticed a very good point. I have updated my answer. thanks.
3

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)

Comments

2

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'

Comments

1

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

Comments

1

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

Comments

1

Nice one-liner generator:

l = 'acbdc'
next(e for e in l if l.count(e)>1)

Or following the rules in the comments to fit the "abba" case:

l = 'acbdc'
next(e for c,e in enumerate(l) if l[:c+1].count(e)>1)

6 Comments

This doesn't work for a string like abba. It will return a. To generalize, you are assuming that the first repeated character also appears in order previously in the string
Isn't a the first character that was repeated?
No, b is the first character to be repeated. a is repeated after b
Well then I misinterpretted the question. BigBadBison also does this.
@ᴡʜᴀᴄᴋᴀᴍᴀᴅᴏᴏᴅʟᴇ3000 The second solution does fix it but it isn't as efficient as Sunitha's answer, which solves it in O(n). Still a good alternative though.
|
0

If complexity is not an issue then this will work fine.

letters = 'acbdc'
found = False
for i in range(0, len(letters)-1):
    for j in range(i+1, len(letters)):
        if (letters[i] == letters[j]):
            print (letters[j])
            found = True
            break
    if (found):
        break

Comments

0

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'.

Comments

0
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"))

Comments

0
str_24 = input("Enter the string:")
for i in range(0,len(str_24)):
    first_repeated_count = str_24.count(str_24[i])
    if(first_repeated_count > 1):
       break
print("First repeated char is:{} and character is 
      {}".format(first_repeated_count,str_24[i]))

Comments

0

You can use regular expressions for this task.

import re
def find_first_duplicate(input_string):
    pattern = re.compile(r'(\w)\1')
    answer = pattern.findall(input_string)
    if not answer: 
        return None
    else:
        return answer[0]

In this code:

  • 1st Capturing Group \w matches any word character (equivalent to [a-zA-Z0-9_])
  • \1 matches the same text as most recently matched by the 1st capturing group

1 Comment

Thank you for contributing to the Stack Overflow community. This may be a correct answer, but it’d be really useful to provide additional explanation of your code so developers can understand your reasoning. This is especially useful for new developers who aren’t as familiar with the syntax or struggling to understand the concepts. Would you kindly edit your answer to include additional details for the benefit of the community?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.