尽管在一定范围内迭代,但字符串索引超出范围

我正在尝试使用Python构建强大的密码检查器。密码的条件如下:

  • 它至少包含6个字符,最多20个字符。
  • 它必须包含至少一个小写字母,至少一个大写字母, 至少一位数字。
  • 它不能连续包含三个重复字符(假设满足其他条件,“ ... aaa ...”弱,但是“ ... aa ... a ...”强)。

编写一个功能StrongPasswordChecker(s),该函数将字符串s作为输入,并返回使s为强密码所需的MINIMUM更改。如果s已经很强,则返回0。

插入,删除或替换任何一个字符都被视为一项更改。

以下是我的尝试:

import re

class Solution:
    def strongPasswordChecker(self,s: str) -> int:

        # Holds the change
        change = 0

        # Checks if the password length is less than 6
        if len(s) < 6:
            change += 6 - len(s)

        # Checks if the password length is greater than 20
        elif len(s) > 20:
            change += len(s) - 20

        # Checks if the password has at least one digit
        elif re.search(r'\d',s):
            change += 1

        # Checks if the password has at least one upper case letter
        elif re.search(r'[A-Z]',s):
            change += 1

        # Checks if the password has at least one lower case letter
        elif re.search(r'[a-z]',password):
            change += 1

        # Checks for repeating characters
        for i in range(1,len(s)):
            if i >= 3 and i < len(s):
                if s[i] == s[i + 1] and s[i + 1] == s[i + 2]:
                    change += 1

        return change

尽管使用上述if语句检查重复字符,但仍然出现以下错误:

IndexError: String Index out of range

tno1no3 回答:尽管在一定范围内迭代,但字符串索引超出范围

问题是该语句可能会超出范围,例如,i == len(s) - 1s[i + 1]s[i + 2]都将超出范围。

for i in range(1,len(s)):
    if i >= 3 and i < len(s):
        if s[i] == s[i + 1] and s[i + 1] == s[i + 2]:
            change += 1

如果您要确保没有3个或更长的组,我会使用itertools.groupby

>>> any(len(list(g)) > 2 for k,g in groupby('aabbcc'))
False
>>> any(len(list(g)) > 2 for k,g in groupby('aabbbbbcc'))
True

要替换代码中的for循环,请像这样使用

elif any(len(list(g)) > 2 for k,g in groupby(s)):
    change += 1
本文链接:https://www.f2er.com/2809513.html

大家都在问