Tutorialspoint
Problem
Solution
Submissions

Generate Random Passwords

Certification: Intermediate Level Accuracy: 50% Submissions: 12 Points: 15

Write a Python function to generate a random password of a specified length. The password should include a mix of uppercase letters, lowercase letters, digits, and special characters.

Example 1
  • Input: length = 8
  • Output: "A1b@C2d#" (Note: actual output will vary due to randomness)
  • Explanation:
    • Step 1: Define character sets for uppercase letters, lowercase letters, digits, and special characters.
    • Step 2: Ensure the password includes at least one character from each set.
    • Step 3: Generate remaining characters randomly from all available character sets.
    • Step 4: Shuffle all characters to ensure randomness in the final password.
    • Step 5: Return the generated password of length 8 with characters from all required sets.
Example 2
  • Input: length = 12
  • Output: "Xy3$Zq9&Wp7*" (Note: actual output will vary due to randomness)
  • Explanation:
    • Step 1: Define character sets for uppercase letters, lowercase letters, digits, and special characters.
    • Step 2: Ensure the password includes at least one character from each set.
    • Step 3: Generate remaining characters randomly from all available character sets.
    • Step 4: Shuffle all characters to ensure randomness in the final password.
    • Step 5: Return the generated password of length 12 with characters from all required sets.
Constraints
  • 4 <= length <= 20
  • Time Complexity: O(n) where n is the length of the password
  • Space Complexity: O(n)
Control StructuresFunctions / MethodsGoogleGoldman Sachs
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use the random module to select characters randomly.
  • Ensure the password contains at least one character from each category (uppercase, lowercase, digit, special character).
  • Combine the selected characters to form the password.

Steps to solve by this approach:

 Step 1: Import necessary modules (random and string)
 
 Step 2: Define character sets for uppercase, lowercase, digits, and special characters  
 Step 3: Create an empty list to build the password  
 Step 4: Add at least one character from each character set to ensure complexity  
 Step 5: Fill the remaining length with random characters from all sets combined  
 Step 6: Shuffle the password list to randomize character positions  
 Step 7: Join the list into a string and return the generated password

Submitted Code :