vendredi 31 mai 2019

Creating a file of max length characters, with a word inserted at random locations x amount of times

I am able to create the random data file but when trying to insert the word at random locations x amount of times, the length of the file becomes greater than the max length passed in.

I have tried creating a file with random characters - length of word*amount of times it needs to be inserted and then adding it to the random locations but that just led to it being appended to the end of the file.

def gen_file(word:str, frequency:int, maxlength:int):
    contents = ''
    i = 0

    while i < frequency:
        for x in range(0, maxlength):
            ran_num = random.randint(0, maxlength-1)
            if x == ran_num:
                contents = contents + word
                i = i+1
            else:
                contents = contents + random.choice(string.ascii_letters)

    file = open("new.txt","w")
    file.write(file_contents)
    file.close()

If I call the function as gen_file('hello', 3, 5000). I expect the output file to be 5000 characters long with 'hello' inserted at 3 random locations but I get an output file that ranges anywhere from 10,000 - 20,000 characters.




Aucun commentaire:

Enregistrer un commentaire