1. 编写函数实现字符串加密和解密,循环使用指定密钥,采用简单的异或算法
def crypt(source,key):
from itertools import cycle
func = lambda x,y:chr(ord(x)^ord(y))
return ''.join(map(func,source,cycle(key)))
source = 'Beautiful is better than ugly'
key = 'Python'
en = crypt(source,key)
de = crypt(en,key)
2. 统计一段文字中每个词出现的次数
基本思路:使用python扩展库jieba的cut()函数对给定的字符串进行分词,然后使用python标准库collections的Counter类统计每个词出现的次数
from collections import Counter
from jieba import cut
def frequency(text):
return Counter(cut(text))
text = "八百标兵奔北坡,北坡八百炮兵炮,标兵怕碰炮兵炮"
print(frequency(text))
3. 检查并判断密码字符串的安全强度
基本思路:遍历字符串中的每个字符,统计字符串中是否包含数字字符,大小写字符和标点符合,根据包含的字符种类的数量来判断字符串作为密码时的安全强度。
import string
def check(pwd):
if not isinstance(pwd,str) or len(pwd) <6:
return 'not suitable for password'
d = {1:'week',2:'below middle',3:'above middle',4:'strong'}
r = [False] * 4
for ch in pwd:
if not r[0] and ch in string.digits:
r[0] = True
elif not r[1] and ch in string.ascii_lowercase:
r[1] = True
elif not r[2] and ch in string.ascii_uppercase:
r[2] = True
elif not r[3] and ch in ',.!;?<>':
r[3] = True
return d.get(r.count(True),'error')
print(check('a2cd,'))
print(check('1234567890'))