1. 程式人生 > >每日一練 no.13

每日一練 no.13

題目:

密碼生成器,輸入位數返回密碼,要求混合使用小寫字母,大寫字母,數字和符號

解答:

靈活使用random

import string
import random
def get_password_normal(size, chars):
    return ''.join(random.choice(chars) for _ in range(size))
    
if __name__ == "__main__":
    # chars = string.printable[:-2]
    chars = "abcdefghi[email protected]#$%^&*()?"
size = int(input('獲得密碼位數(4~12):')) passwd = get_password_normal(size, chars) print(passwd)

生成強密碼(大小寫字母,數值,符號 都要包括在內): 思路一:隨機生成密碼,判斷是否滿足要求,滿足要求則返回

import random
import string

def get_password_strong(size, chars):
    chars_class = [string.ascii_lowercase, string.ascii_uppercase, string.
digits, '[email protected]#$%^&*()?'] while True: judgment = [1 for _ in range(4)] passwd = ''.join(random.choice(chars) for _ in range(size)) for i, item in enumerate(chars_class): if any([1 if j in item else 0 for j in passwd]): judgment[
i] = 0 if not any(judgment): return passwd break if __name__ == "__main__": chars = "a[email protected]#$%^&*()?" size = int(input('獲得密碼位數(4~12):')) passwd = get_password_strong(size, chars) print(passwd)

思路二:將密碼位數分配到四個部分,再隨機選取,然後shuffle

import random
import string

def get_password_strong(size):
    chars_class = [string.ascii_lowercase, string.ascii_uppercase, string.digits, '[email protected]#$%^&*()?']    
    num_pick = sorted(random.sample(range(1, size), 3))
    num_pick.insert(0, 0)
    num_pick.append(size)
    pick_lsit = list((map(lambda x,y:y-x ,num_pick[:-1],num_pick[1:])))
    passwd_list = []
    for i, item in enumerate(chars_class):
        passwd_list.extend([random.choice(item) for _ in range(pick_lsit[i])])
     # 重新排序
    random.shuffle(passwd_list)        
    return ''.join(passwd_list)
    
if __name__ == "__main__":
    size = int(input('獲得密碼位數(4~12):'))
    passwd = get_password_strong(size)
    print(passwd)