Home > Software design >  Check if there are different characters between two same characters?
Check if there are different characters between two same characters?

Time:09-29

"abcda" should pass, because it starts with a and ends with a. "aaabcdd" should failed because it starts with a,but does not end with a.

I tried to do it by (.)(?!.*\1)\1, but it failed

CodePudding user response:

Assuming you want to find out if all occurrences of the same character within a string are in the same cluster, you could use itertools.groupby:

from itertools import groupby

def clustered(string):
    seen = set()
    for k, _ in groupby(string):
        if k in seen:
            return True
        seen.add(k)
    return False

>>> clustered("abcda")
True
>>> clustered("aaabcddd")
False

CodePudding user response:

Here is some code that presents the answer to your question:

def should_pass(letters):
    if (letters[0] == 'a') and (letters[-1] == 'a'):
        return True
    else:
        return False

It takes the first and last index of the letters string and checks if they are both equivalent to a. If you didn't know, the last index can be grabbed by the [-1] index.

  • Related