在尝试获取唯一事件时,set 非常有用。此代码使用set 将密码转换为一组唯一字符。然后它使用sum 来计算这些唯一字符出现in 特殊列表的次数。
代码:
def unique_special_count(password):
# provide a list of special characters
special = '''!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~ '''
# turn the password into a set of unique characters
# then sum the number of times these unique are in special list
return sum(ch in special for ch in set(password))
测试代码:
test_passwords = (
('notspecial', 0),
('one_special', 1),
('one_special_twice', 1),
('two_specials!', 2),
('three_specials!?', 3),
('three_specials_twice!?!', 3),
)
for pw, count in test_passwords:
print(pw, count, unique_special_count(pw))
assert count == unique_special_count(pw)
结果:
notspecial 0 0
one_special 1 1
one_special_twice 1 1
two_specials! 2 2
three_specials!? 3 3
three_specials_twice!?! 3 3