可以缩短或改进此代码吗? [英] can this code be shortened or improved?
问题描述
可以缩短/改善吗?我正在尝试在python中进行密码检查.
Can this be shortened/improved? I'm trying to make a password checker in python.
是否可以将if放入for循环中?如果可以,怎么办?
Could the if's be put into a for loop? And if so, how?
pw = input("Enter password to test: ")
caps = sum(1 for c in pw if c.isupper())
lower = sum(1 for c in pw if c.islower())
nums = sum(1 for c in pw if c.isnumeric())
scr = ['weak', 'medium', 'strong']
r = [caps, lower, nums]
if len(pw) < 6:
print("too short")
elif len(pw) > 12:
print("too long")
if caps >= 1:
if lower >= 1:
if nums >= 1:
print(scr[2])
elif nums < 1:
print("your password is " + scr[1])
elif lower < 1:
print("your password strength is " + scr[0])
elif caps < 1:
print("your password strength is " + scr[1])
感谢您的任何建议:D
Thanks for any suggestions :D
推荐答案
caps = sum(1 for c in pw if c.isupper())
可以是:
caps = sum(c.isupper() for c in pw)
if caps >= 1:
可以是:
if caps:
最显着的改进:可以完全移除底部的if
/elif
块
The most significant improvement: The bottom if
/elif
block can be completely removed by doing
i_strength = sum(map(bool,[caps,lower,nums])) - 1 #or sum(map(bool,r)) - 1
print('your password is {}'.format(scr[i_strength]))
说明:map(bool,[caps,lower,nums])
累加每个caps,lower,nums
不为零的次数.将它们与sum
相加会为您提供强度",您已经方便地将其放入了列表中,可以通过索引进行访问.
Explanation: map(bool,[caps,lower,nums])
accumulates how many times each of caps,lower,nums
is non-zero. Adding them up with sum
gives you your "strength", which you've conveniently already put into a list, which can be accessed by index.
所有这些改进都利用了python中虚假"的概念,在布尔上下文中也称为对象的值.通常,空值和零值是False
,对布尔值求和就等于加一和零,因此就可以了.
All of these improvements leverage the concept of "falsiness" in python, otherwise known as an object's value in a boolean context. Generally empty and zero things are False
, and summing booleans is equivalent to adding ones and zeroes, so there you go.
当然,除了检查它们是否为非零之外,似乎您没有在做带有高/低/数字计数的事情.所以清理只是
Of course, it doesn't seem that you're doing anything with the counts of upper/lower/nums other than checking if they're nonzero. So a cleanup would just be
caps = any(c.isupper() for c in pw)
...
然后
i_strength = sum([caps,lower,nums]) -1
这篇关于可以缩短或改进此代码吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!