[英]Best way to optimize if with three unknowns?
I made this code to generate a password as an exercise but I would like to know if there is a smarter way to use the if
.我制作了这段代码来生成密码作为练习,但我想知道是否有更聪明的方法来使用if
。 I feel bad to list all the possible cases stupidly.愚蠢地列出所有可能的情况,我感到很糟糕。 Trying to put the if
in the others if
it becomes incomprehensible. 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)
Thank you: Also if anything else in the code is uggly tell me )谢谢:另外,如果代码中的其他内容很丑,请告诉我)
You can build the regex string based on input:您可以根据输入构建正则表达式字符串:
reg = '[a-z'
if upc: reg += "A-Z"
if nbr: reg += "\\d"
if spe: reg += "_$.+-/*="
reg += "]"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.