mardi 26 janvier 2021

Generate random string to match the goal string with minimum iteration and control statements

The following is my python code to find the number of iterations needed to generate random string iteratively to match the input string.

Here I have repeated a similar kind of for loop in both the functions randomString() and betterString(). I tried to avoid it but couldn't. I want this to be combined together into a single generateString() function with minimum iteration statements. Any suggestions to make it so or any other possible way to make the code better without complicating much?

The input is any string statements like "Hello, World! How Are Y@u doiNG?" and the output is the number of iterations needed to match the input string e.g 408. Your suggestions to improve the code will be helpful.

import random


def randomString():
    global stringLen
    stringLen = len(goalString)
    global alphanum
    alphanum = '''abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ !@#&()–[{}]:;‘,'?/*1234567890'''
    global alphaLen
    alphaLen = len(alphanum)
    randomString = ''
    for i in range(stringLen):
        randomString = randomString + alphanum[random.randrange(alphaLen)]
    
    return randomString 
            
def betterString():
    betterString = randomString()
    newString = ''
    iteration = 1 #included the iteration of randomString()
    while betterString != goalString:
        charIndex = [i for i in range(stringLen) if betterString[i] == goalString[i]]
        for i in range(stringLen):
            if i in charIndex:
                newString = newString + betterString[i]
            else:
                newString = newString + alphanum[random.randrange(alphaLen)]
                    
        betterString = newString
        newString = ''
        iteration = iteration + 1
    
    return iteration

goalString = input()
print(betterString())



Aucun commentaire:

Enregistrer un commentaire