Signup/Sign In

Python Program to generate random strings until a given string is generated

In this tutorial, you will learn to write a program where we have to generate random strings until a given string is generated in Python. We will be generating a random combination of letters and numbers until the desired string is printed.

A string can have letters in both uppercase and lowercase, numbers, special symbols, and punctuations so we have to consider these constraints when creating random sequences.

Look at the examples to understand the input and output format.

Input: "abc"

Output:

zL6
nWD
.

.

.

abc
Target matched after 141 iterations

Input: "aa"

Output:

EO

.

.

4a
aa
Target matched after 15 iterations

Approach For Creating Program

To solve this problem, we will take into consideration that the string is made up of ASCII characters. We will be using some common string operations which will define the constraints of a string.

In a variable, we will store all the possible characters which the string can have by combining values of some string constants in Python.

We will combine string.ascii_lowercase, string.ascii_uppercase, string.digits and a string constant containing punctuations ( . , ! ? ; : ) to get the possible characters.

Then we have to randomly generate strings which will be done using random() function in Python. It is a built-in function that returns random values.

We will use two loops in our program, one to show all the possible combinations that can be provided by the random function and the other which matches the random strings to the given string. If both the strings match we will stop the loop.

Look at the algorithm to understand the working of the program.

Algorithm

Step 1- Import modules in the program

Step 2- Declare a variable that will have all the possible ASCII characters

Step 3- Declare string which has to be generated

Step 4- Generate random strings from the variable which has all possible ASCII values

Step 5- Declare a boolean variable that will be used to break out of the loop, set its value to False

Step 6- Run another loop to print the generated random strings

Step 7- Run a loop till the boolean variable is true, to match the random string to the string which has to be generated

Step 8- If the required string is generated update the boolean value to false to stop the loop

Step 9- Else, move to the next iteration

Step 10- Use time.sleep(0.1) after the string is matched, to stops the execution of the current thread

Step 11- Print the iteration after which the required string has been generated

Python Program

To use string operations, random() method, and delay() method we will have to import string, random, and time modules in the program.

# generate random strings
import string
import random
import time
  
# all possible characters including lowercase, uppercase and punctuations
possibleChar = string.ascii_lowercase + string.digits + string.ascii_uppercase + ' ., !?;:'
  
# string to be generated
t = "test"
  
attemptThis = ''.join(random.choice(possibleChar) for i in range(len(t)))
attemptNext = ''
  
done= False
iteration = 0
  
# Iterate while done is false
while done == False:
    print(attemptThis)
      
    attemptNext = ''
    done = True
      
    # if matches with string 
    # change index
    for i in range(len(t)):
        if attemptThis[i] != t[i]:
            done = False
            attemptNext += random.choice(possibleChar)
        else:
            attemptNext += t[i]
              
    # increase iteration
    iteration = iteration + 1
    attemptThis = attemptNext
    time.sleep(0.1)

print("Target matched after ",iteration," iterations")


kAc5
ohbj
.
.
.
test
Target matched after 194 iterations

Conclusion

In this tutorial, we have seen how to generate random strings until a required string is generated. We have discussed how to use the common string operations and random() function in our program.