Code to output the first repeated character in given string?

后端 未结 9 2130
日久生厌
日久生厌 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:56

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

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

    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)
    
    0 讨论(0)
提交回复
热议问题