Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python Program to Generate Random String With Uppercase And Digits
Next article icon

Generating random strings until a given string is generated

Last Updated : 01 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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.


Next Article
Python Program to Generate Random String With Uppercase And Digits

M

MrinalVerma
Improve
Article Tags :
  • Project
  • Python
  • Python Programs
Practice Tags :
  • python

Similar Reads

  • Generate Random String Without Duplicates in Python
    When we need to create a random string in Python, sometimes we want to make sure that the string does not have any duplicate characters. For example, if we're generating a random password or a unique identifier, we might want to ensure each character appears only once. Using random.sample()Using ran
    2 min read
  • Python Program to Generate Random binary string
    Given a number n, the task is to generate a random binary string of length n.Examples: Input: 7 Output: Desired length of random binary string is: 1000001 Input: 5 Output: Desired length of random binary string is: 01001 Approach Initialize an empty string, say key Generate a randomly either "0" or
    2 min read
  • Python - Generate Random String of given Length
    Generating random strings is a common requirement for tasks like creating unique identifiers, random passwords, or testing data. Python provides several efficient ways to generate random strings of a specified length. Below, we’ll explore these methods, starting from the most efficient. Using random
    2 min read
  • Python Program to Generate Random String With Uppercase And Digits
    Generating a series of random strings can help create security codes. Besides, there are many other applications for using a random string generator, for instance, obtaining a series of numbers for a lottery game or slot machines. A random string generator generates an alphanumeric string consisting
    3 min read
  • Python - Create a string made of the first and last two characters from a given string
    To solve the problem, we need to create a new string that combines the first two and the last two characters of a given string. If the input string is too short (less than 2 characters), we should return an empty string. This task is simple and can be achieved using a variety of methods. Using slici
    2 min read
  • Python | Get the starting index for all occurrences of given substring
    Given a string and a substring, the task is to find out the starting index for all the occurrences of a given substring in a string. Let's discuss a few methods to solve the given task. Method #1: Using Naive Method C/C++ Code # Python3 code to demonstrate # to find all occurrences of substring in #
    3 min read
  • Python | Get the substring from given string using list slicing
    Given a string, write a Python program to get the substring from given string using list slicing. Let’s try to get this using different examples. What is substring? A substring is a portion of a string. Python offers a variety of techniques for producing substrings, as well as for determining the in
    4 min read
  • Print Substrings that are Prefix of the Given String - Python
    The task of printing the substrings that are prefixes of a given string involves generating all the possible substrings that start from the first character of the string and end at any subsequent position.For example, if the given string is s = "hello", the prefixes of the string would include "h",
    3 min read
  • Python Program To Check If A String Is Substring Of Another
    Given two strings s1 and s2, find if s1 is a substring of s2. If yes, return the index of the first occurrence, else return -1. Examples :  Input: s1 = "for", s2 = "geeksforgeeks" Output: 5 Explanation: String "for" is present as a substring of s2. Input: s1 = "practice", s2 = "geeksforgeeks" Output
    3 min read
  • Extract all integers from a given String
    Given a string str, extract all integers words from it. Example: Input: str = "1Hello2 &* how are y5ou"Output: 1 2 5 Input: str = "Hey everyone, I have 500 rupees and I would spend a 100"Output: 500 100 Approach: To solve this problem follow the below steps: Create a string tillNow, which will s
    9 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences