我认为我有正确的想法来解决这个问题,但我不确定为什么 我没有在docstring中显示所需的结果。有人可以帮我解决这个问题吗?
def check_password(s):
'''(str, bool)
>>> check_password('TopSecret')
False
>>> check_password('TopSecret15')
True
'''
for char in s:
if char.isdigit():
if char.islower():
if char.isupper():
return True
else:
return False
答案 0 :(得分:2)
你的逻辑是有缺陷的,应该是这样的:
def check_password(s):
has_digit = False
has_lower = False
has_upper = False
for char in s:
if char.isdigit():
has_digit = True
if char.islower():
has_lower = True
if char.isupper():
has_upper = True
# if all three are true return true
if has_digit and has_upper and has_lower:
return True
else:
return False
现在,让我们谈谈你的代码有什么问题。
def check_password(s):
for char in s:
if char.isdigit():
if char.islower(): # we only get to this check if char was a digit
if char.isupper(): # we only get here if char was a digit and lower
# it is not possible to get here
# char would have to be a digit, lower, and upper
return True
else:
return False
作为一个例子让我们看看TopSecret15,我们从T
开始isdigit
= False因此我们会立即为“T' isdigit
是真的,但是islower
会是假的,所以它再次返回false 你是否看到所有这三个对于同一个char都是不可能的?
您的代码相当于:
if char.isdigit and char.islower and char.isupper:
# this will never happen
答案 1 :(得分:1)
这不起作用的原因是,对于任何给定的角色,它首先检查它是否是数字,然后如果它低,那么它是否为高。显然,一个角色不可能同时属于这三个角色。您想要检查每个字符以查看它是数字,小写还是大写,然后翻转一个布尔值,如has_upper
。然后,在for
循环之后,您将检查是否所有布尔值都为真。
答案 2 :(得分:0)
看到这个答案: https://stackoverflow.com/a/2990682/7579116 检查密码是否符合所有要求的最佳方法是使用正则表达式。
答案 3 :(得分:0)
我已经离开了这里(因为我觉得我很无聊)并且掀起了一个可扩展的密码检查系统。也许这将有助于澄清为什么你的版本没有做你想要的(或者可能不会)。
您的代码的基本问题是它会检查单个特征,而不是所需特征的每个。
def check_password(password):
# These are the characteristics we want a password to have:
characteristics = [
length(8), # At least 8 characters
lower_case(1), # At least 1 lower case letter
upper_case(1), # At least 1 upper case letter
number(1), # At least 1 number
]
# Check to see if the supplied password has *all* of the desired
# characteristics:
return all(
characteristic(password)
for characteristic in characteristics
)
def length(n=10):
# Ensure password has at least N characters
def check(password):
return len(password) >= n
return check
def lower_case(n=1):
# Ensure password has at least N lower case characters
def check(password):
count = 0
for char in password:
if char.islower():
count += 1
if count == n:
return True
return False
return check
def upper_case(n=1):
# Ensure password has at least N upper case characters
def check(password):
count = 0
for char in password:
if char.isupper():
count += 1
if count == n:
return True
return False
return check
def number(n=1):
# Ensure password has at least N numbers
def check(password):
count = 0
for char in password:
if char.isdigit():
count += 1
if count == n:
return True
return False
return check
# Doesn't have any numbers:
>>> print(check_password('TopSecret'))
False
# Acceptable:
>>> print(check_password('TopSecret15'))
True
# Has lower case, upper case, and number, but it's not long enough:
>>> print(check_password('Ab1'))
False
注意:
check
函数可以成为单行)。