lundi 1 juin 2020

Fastest method to generate random lines of strings with certain length in python

I have been looking for a way to generate, for example, a random 6 character string every line

Problem is, I feel like my code is slow:

import random
import string
import threading

length = int(input("length:"))


def MainCode():
    while 1 == 1:
        letters = string.ascii_lowercase
        actual_random = ''.join(random.choice(letters) for i in range(length))
        print(actual_random)
        towrite = open("TestSpeed.txt","a")
        towrite.write(actual_random + "\n")
        towrite.close()

while the code works, It was very slow for what I wanted

I have looked into this thread and this code is super fast and works amazingly: Fastest method to generate big random string with lower Latin letters

it only prints to console rather than write to a file (Which I'm not sure if it effects the speed)

the code:

import os
import sys

nbytes = 256
nletters = 26
naligned = nbytes - (nbytes % nletters)
tbl = bytes.maketrans(bytearray(range(naligned)),
                      bytearray([ord(b'a') + b % nletters
                                 for b in range(naligned)]))
bytes2delete = bytearray(range(naligned, nbytes))
R = lambda n: os.urandom(n).translate(tbl, bytes2delete)

def write_random_ascii_lowercase_letters(write, n):
    """*write* *n* random ascii lowercase letters."""    
    while n > 0:
        # R(n) expected to drop `(nbytes - nletters) / nbytes` bytes
        # to compensate, increase the initial size        
        n -= write(memoryview(R(n * nbytes // naligned + 1))[:n])

write = sys.stdout.buffer.write
write_random_ascii_lowercase_letters(write, 1000000)

Problem is, I literally can't understand a thing, just a bit here and there but nothing on the main stuff I tried searching for other simpler methods but couldn't find any, also youtube videos weren't that much of a help either

What I'm trying to do is generate a file with an X amount of lines, each line is X characters long , I thought about adding the ability to choose which characters to include in the strings (underscores, capital, small... etc), but first I want to know what's the code doing so I can do it properly

I'm kinda new to programming and Python in general, so sorry for any obvious mistakes




Aucun commentaire:

Enregistrer un commentaire