Code to output the first repeated character in given string?

后端 未结 9 2129
日久生厌
日久生厌 2021-01-21 15:23

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

相关标签:
9条回答
  • 2021-01-21 15:41

    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
    
    0 讨论(0)
  • 2021-01-21 15:42

    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

    0 讨论(0)
  • 2021-01-21 15:42

    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

    0 讨论(0)
  • 2021-01-21 15:42
    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"))
    
    
    0 讨论(0)
  • 2021-01-21 15:50

    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'
    
    0 讨论(0)
  • 2021-01-21 15:55

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

    0 讨论(0)
提交回复
热议问题