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



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

  • 它至少有 6 个字符,最多 20 个字符。
  • 它必须至少包含一个小写字母,至少一个大写字母, 和至少一位数字。
  • 它不得连续包含三个重复字符("...啊..."很弱,但是"...机 管 局。。。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

问题是这个语句可能会越界,例如,当i == len(s) - 1时,s[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

最新更新