Movatterモバイル変換


[0]ホーム

URL:


Open In App
Next Article:
Print Alphabets till N-Python
Next article icon

The task of generating randomstrings 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
importstringimportrandom# Possible characterspossibleCharacters=string.ascii_lowercase+string.digits+ \string.ascii_uppercase+' ., !?;:'# Target stringt="geek"# Generate initial random stringdefgenerate_random_string(length):return''.join(random.choice(possibleCharacters)for_inrange(length))# Fitness function: count matching charactersdeffitness(current):returnsum(1fora,binzip(current,t)ifa==b)# Mutation function: change one random characterdefmutate(parent):index=random.randint(0,len(parent)-1)child=list(parent)child[index]=random.choice(possibleCharacters)return''.join(child)# Main evolution loopattempt=generate_random_string(len(t))iteration=0whileattempt!=t:print(attempt)new_attempt=mutate(attempt)# Keep the mutation only if it improves fitnessiffitness(new_attempt)>=fitness(attempt):attempt=new_attemptiteration+=1print(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 ast.
  • Defines Fitness Function counts matching characters in the correct positions.
  • Mutation Function changes one random character in the string
  • Main Evolution Loopstarts 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

TheHill 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
importstringimportrandom# Possible characterspossibleCharacters=string.ascii_lowercase+string.digits+ \string.ascii_uppercase+' ., !?;:'# Target stringt="geek"# Generate initial random stringdefgenerate_random_string(length):return''.join(random.choice(possibleCharacters)for_inrange(length))# Fitness functiondeffitness(current):returnsum(1fora,binzip(current,t)ifa==b)# Main hill-climbing loopattempt=generate_random_string(len(t))iteration=0whileattempt!=t:print(attempt)new_attempt=list(attempt)foriinrange(len(t)):ifnew_attempt[i]!=t[i]:new_attempt[i]=random.choice(possibleCharacters)iffitness(''.join(new_attempt))<fitness(attempt):new_attempt[i]=attempt[i]# Revert change if worseattempt=''.join(new_attempt)iteration+=1print(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 modulesimportstringimportrandomimporttime# All possible characters including lowercase, uppercase, and special symbolspossibleCharacters=string.ascii_lowercase+string.digits+ \string.ascii_uppercase+' ., !?;:'# String to be generatedt="geek"# To take input from the user# t = input(str("Enter your target text: "))attemptThis=''.join(random.choice(possibleCharacters)foriinrange(len(t)))attemptNext=''completed=Falseiteration=0# Iterate while completed is falsewhilecompleted==False:print(attemptThis)attemptNext=''completed=True# Fix the index if matches with the string to be generatedforiinrange(len(t)):ifattemptThis[i]!=t[i]:completed=FalseattemptNext+=random.choice(possibleCharacters)else:attemptNext+=t[i]# Increment the iterationiteration+=1attemptThis=attemptNexttime.sleep(0.1)# Driver Codeprint("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:

  • attemptThisstarts 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.

Improve
Practice Tags :

Similar Reads

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 ourCookie 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

[8]ページ先頭

©2009-2025 Movatter.jp