繁体   English   中英

如果有三个未知数,优化的最佳方法是什么?

[英]Best way to optimize if with three unknowns?

我制作了这段代码来生成密码作为练习,但我想知道是否有更聪明的方法来使用if 愚蠢地列出所有可能的情况,我感到很糟糕。 if变得难以理解,则尝试将if放在其他人中。

import random
import re
import exrex

len_pwd = int(input('Length of the password : '))
upc = int(input('Upper case ? (0 = No ; 1 = Yes) : '))
nbr = int(input('Numbers ? (0 = No ; 1 = Yes) : '))
spe = int(input('Special char ? (0 = No ; 1 = Yes) : '))

pwd = ''

for i in range(len_pwd):
    if upc and not nbr and not spe:
        a = exrex.getone('[a-zA-Z]')
        pwd += a
    elif nbr and not upc and not spe:
        a = exrex.getone('[a-z\d]')
        pwd += a
    elif spe and not upc and not nbr:
        a = exrex.getone('[a-z"_$.+-/*=]')
        pwd += a
    elif nbr and spe and not upc:
        a = exrex.getone('[a-z\d"_$.+-/*=]')
        pwd += a
    elif upc and nbr and not spe:
        a = exrex.getone('[a-zA-Z\d]')
        pwd += a
    elif upc and spe and not nbr:
        a = exrex.getone('[a-zA-Z"_$.+-/*=]')
        pwd += a
    elif not upc and not nbr and not spe:
        print("Don't bother me.")
        break
    else:
        a = exrex.getone('[a-zA-Z\d"_$.+-/*=]')
        pwd += a

print(pwd)

谢谢:另外,如果代码中的其他内容很丑,请告诉我)

您可以根据输入构建正则表达式字符串:

reg = '[a-z'
if upc: reg += "A-Z"
if nbr: reg += "\\d"
if spe: reg += "_$.+-/*="
reg += "]"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM