Back to Freecodecamp

Step 61

curriculum/challenges/english/blocks/learn-regular-expressions-by-building-a-password-generator/6577319039f4f7de9251b822.md

latest2.3 KB
Original Source

--description--

Instead of using a loop and a counter variable, you can achieve the same result with a different approach, which you are going to implement in the next few steps.

all() is a built-in Python function that returns True if all the elements inside a given iterable evaluate to True. Otherwise, it returns False.

Replace your existing for loop and two if statements with a single if statement. For the if condition, use a call to the all() function and pass an empty list as the argument to the function call.

--hints--

You should replace your existing for loop and two if statements with a single if statement.

js
({ test: () => {
  assert.match(code, /^(\s{8})if\s+.+:\s*^\1\s{4}break/ms);
  assert.isFalse(/if\s+count\s*==\s*4\s*:/.test(code));
} })

Your new if condition should be all([]).

js
({ test: () => assert(runPython(`
  _Node(_code).find_function("generate_password").find_while("True").find_bodies()[0].find_if("all([])") != _Node()
`)) })

You should have break inside your new if body.

js
({ test: () => assert(runPython(`
  _Node(_code).find_function("generate_password").find_while("True").find_bodies()[0].find_if("all([])").find_bodies()[0].is_equivalent("break")
`)) })

--seed--

--seed-contents--

py
import re
import secrets
import string


def generate_password(length, nums, special_chars, uppercase, lowercase):
    # Define the possible characters for the password
    letters = string.ascii_letters
    digits = string.digits
    symbols = string.punctuation

    # Combine all characters
    all_characters = letters + digits + symbols

    while True:
        password = ''
        # Generate password
        for _ in range(length):
            password += secrets.choice(all_characters)
       
        constraints = [
            (nums, r'\d'),
            (lowercase, r'[a-z]'),
            (uppercase, r'[A-Z]'),            
            (special_chars, fr'[{symbols}]')            
        ]

        # Check constraints
        count = 0
--fcc-editable-region--
        for constraint, pattern in constraints:
            if constraint <= len(re.findall(pattern, password)):
                count += 1
            
        if count == 4:
--fcc-editable-region--
            break

    return password

# new_password = generate_password(8)
# print(new_password)