Generating random strings until a given string is generated
Last Updated :
01 Mar, 2025
The task of generating random strings until a given string is generated involves using random combinations of characters and progressively improving the string through mutations until the target string is matched. For example, given a target string like "geek," the goal is to keep generating random strings until one exactly matches "geek."
Using genetic algorithm
Genetic Algorithm is an evolutionary approach where we generate a random string and progressively improve it through mutation. Instead of completely regenerating a new string every time, we modify the existing one by changing one character at a time, ensuring each change brings us closer to the target.
Python
import string
import random
# Possible characters
possibleCharacters = string.ascii_lowercase + string.digits + \
string.ascii_uppercase + ' ., !?;:'
# Target string
t = "geek"
# Generate initial random string
def generate_random_string(length):
return ''.join(random.choice(possibleCharacters) for _ in range(length))
# Fitness function: count matching characters
def fitness(current):
return sum(1 for a, b in zip(current, t) if a == b)
# Mutation function: change one random character
def mutate(parent):
index = random.randint(0, len(parent) - 1)
child = list(parent)
child[index] = random.choice(possibleCharacters)
return ''.join(child)
# Main evolution loop
attempt = generate_random_string(len(t))
iteration = 0
while attempt != t:
print(attempt)
new_attempt = mutate(attempt)
# Keep the mutation only if it improves fitness
if fitness(new_attempt) >= fitness(attempt):
attempt = new_attempt
iteration += 1
print(f"Target matched after {iteration} iterations")
Output
FyFJ
.:YZ
aubo
.
.
.
g56G
gk6R
g7Se
gT o
gD d
gXek
g0ek
g ek
.
.
gUek
giek
geek
Target matched after 168 iterations
Explanation:
- Generates Random String creates an initial random string of the same length as t.
- Defines Fitness Function counts matching characters in the correct positions.
- Mutation Function changes one random character in the string
- Main Evolution Loop starts with a random string, mutates it, compares fitness, accepts the mutation if fitness is maintained or improved, and repeats until the target is matched.
Using hill climbing approach
The Hill Climbing Algorithm takes a greedy approach by fixing correct characters and modifying only the incorrect ones. This ensures that once a character is correctly positioned, it remains unchanged.
Python
import string
import random
# Possible characters
possibleCharacters = string.ascii_lowercase + string.digits + \
string.ascii_uppercase + ' ., !?;:'
# Target string
t = "geek"
# Generate initial random string
def generate_random_string(length):
return ''.join(random.choice(possibleCharacters) for _ in range(length))
# Fitness function
def fitness(current):
return sum(1 for a, b in zip(current, t) if a == b)
# Main hill-climbing loop
attempt = generate_random_string(len(t))
iteration = 0
while attempt != t:
print(attempt)
new_attempt = list(attempt)
for i in range(len(t)):
if new_attempt[i] != t[i]:
new_attempt[i] = random.choice(possibleCharacters)
if fitness(''.join(new_attempt)) < fitness(attempt):
new_attempt[i] = attempt[i] # Revert change if worse
attempt = ''.join(new_attempt)
iteration += 1
print(f"Target matched after {iteration} iterations")
Output :
FyFJ
.:YZ
aubo
.
.
.
g56G
gk6R
g7Se
gT o
gD d
gXek
g0ek
g ek
.
.
gUek
giek
geek
Target matched after 168 iterations
Explanation:
- new_attempt list: This approach starts by converting the string to a list, allowing individual character manipulation.
- Hill Climbing iterates through each character in the current string, replacing non-matching characters with random ones, and reverts any changes that reduce fitness, ensuring that only improvements or unchanged states are kept.
Using iterative approach
This approach generates an initial random string and progressively replaces incorrect characters with random choices until the entire string matches the target.
Python
# Importing string, random, and time modules
import string
import random
import time
# All possible characters including lowercase, uppercase, and special symbols
possibleCharacters = string.ascii_lowercase + string.digits + \
string.ascii_uppercase + ' ., !?;:'
# String to be generated
t = "geek"
# To take input from the user
# t = input(str("Enter your target text: "))
attemptThis = ''.join(random.choice(possibleCharacters)
for i in range(len(t)))
attemptNext = ''
completed = False
iteration = 0
# Iterate while completed is false
while completed == False:
print(attemptThis)
attemptNext = ''
completed = True
# Fix the index if matches with the string to be generated
for i in range(len(t)):
if attemptThis[i] != t[i]:
completed = False
attemptNext += random.choice(possibleCharacters)
else:
attemptNext += t[i]
# Increment the iteration
iteration += 1
attemptThis = attemptNext
time.sleep(0.1)
# Driver Code
print("Target matched after " +
str(iteration) + " iterations")
Output :
FyFJ
.:YZ
aubo
.
.
.
g56G
gk6R
g7Se
gT o
gD d
gXek
g0ek
g ek
.
.
gUek
giek
geek
Target matched after 168 iterations
Explanation:
- attemptThis starts with a random string.
- For each incorrect character in attemptThis, it is replaced with a random character.
- If the character is already correct, it is preserved.
- This process repeats until the entire string matches the target string.
- time.sleep(0.1) adds a slight delay to visualize the process.
Similar Reads
Python Tutorial | Learn Python Programming Language Python Tutorial â Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly.Python is:A high-level language, used in web development, data science, automatio
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Enumerate() in Python enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Input and Output in Python Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
8 min read