我正在尝试使用Python构建强大的密码检查器。密码的条件如下:
编写一个功能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
答案 0 :(得分:4)
问题是该语句可能会超出范围,例如,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