Home > Net >  Best way to optimize if with three unknowns?
Best way to optimize if with three unknowns?

Time:07-26

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. I feel bad to list all the possible cases stupidly. Trying to put the if in the others if it becomes incomprehensible.

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 :)

CodePudding user response:

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  = "]"
  • Related