def is_password_good(password):
if len(txt) > 7 and [i for i in txt if i.isupper()] and [i for i in txt if i.islower() and [i for i in txt if i.isnumeric()]]:
return True
else:
return False
txt = input()
print(is_password_good(txt))
uj5u.com熱心網友回復:
如果您正在尋找一個大寫字母,使用您正在使用的方法,每個字母都將被評估。因此,如果您的字串中有 50 個字母,并且您正在使用串列理解方法,那么每個串列將執行 50 項操作。在你的情況下,有三個串列推導,所以len(txt) * 3每次都會進行評估。
使用您的方法,使用行內密碼修改以使 timeit 呼叫更簡單:
import timeit
def is_password_good():
txt = "Sup3rlongpassword"
if (
len(txt) > 7
and [i for i in txt if i.isupper()]
and [i for i in txt if i.islower() and [i for i in txt if i.isnumeric()]]
):
return True
else:
return False
>>> timeit.timeit(is_password_good)
17.099690434522927
這是使用正則運算式的方法。在每種情況下,只要滿足通過條件,它就會回傳該值。
import re
has_upper = re.compile('[A-Z]').search
has_lower = re.compile('[a-z]').search
has_digit = re.compile('[0-9]').search
def is_password_good_re():
txt = "Sup3rlongpassword"
if len(txt) > 7 and has_upper(txt) and has_lower(txt) and has_digit(txt):
return True
else:
return False
>>> timeit.timeit(is_password_good_re)
0.8171015260741115
編輯:
其他突出的東西,你的一個串列嵌套在另一個串列中。
[i for i in txt if i.islower() and [i for i in txt if i.isnumeric()]]
所以這意味著每個字符都會進行數字檢查。因此,如果密碼中有 10 個字符,則對數字進行 10 次檢查,每個檢查涉及 10 次檢查,僅對數字進行 100 次評估。
uj5u.com熱心網友回復:
for當您可以運行一個回圈時,您一個接一個地運行三個回圈for:
def is_password_good(password, good_length):
if len(password) < good_length:
return False
has_upper, has_lower, has_digit = False, False, False
for char in set(password):
has_upper = char.isupper() or has_upper
has_lower = char.islower() or has_lower
has_digit = char.isdigit() or has_digit
if has_upper and has_lower and has_digit:
return True
return False
想象一個全小寫字母的密碼——您必須檢查每個字母以查看是否還有數字或大寫字母,因此您將遍歷所有n字符,然后才能明確地說密碼不滿足要求。這意味著在最壞的情況下,您能做的最好的事情就是O(n).
然后的想法應該是盡快跳出回圈- 在這種情況下,一旦所有三個標志都切換到True.
一旦第一次滿足檢查,這三個char.isxxx() or has_xxx陳述句中的每一個都將True永遠存在,因為在第一次滿足之后True,該陳述句將減少為char.isxxx() or True永遠為真。
一旦設定了所有三個標志,您就可以中斷并回傳是否good_length滿足。
uj5u.com熱心網友回復:
您可以將每個method作為您的條件進行迭代,并在滿足條件時中斷以節省資源。
def is_password_good(password):
if len(password) > 7:
password = set(password)
for method in (lambda x: x.isupper(),
lambda x: x.islower(),
lambda x: x.isnumeric()):
for i in password:
if method(i):
break
else:
return False
return True
else:
return False
>>> is_password_good('1234567')
False
>>> is_password_good('12345678')
False
>>> is_password_good('123456aa')
False
>>> is_password_good('123456aB')
True
這種方法:
- 滿足條件時中斷
- 為了避免浪費計算時間檢查被證明是正確的答案
- 時間復雜度為
O(<=n)- 轉換為
set洗掉的重復字母
- 轉換為
- 可擴展以提供更多功能
- 只需向元組添加另一個
lambda函式method
- 只需向元組添加另一個
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/477043.html
標籤:Python python-3.x
上一篇:Sklearn管道轉換特定列-ValueError:要解包的值太多(預期為2)
下一篇:多處理查詢檔案中的新行
